Handle AJAX Video File Upload Using PHP And MariaDB

SECURE VIDEO STORAGE
SECURE VIDEO STORAGE

Live stream set for 2025-10-29 at 14:00:00 Eastern

Ask questions in the live chat about any programming or lifestyle topic.

This livestream will be on YouTube or you can watch below.

Secure Video Uploads: Building the PHP and MariaDB Backend (Part 2)

Welcome back! In [Part 1: The Frontend], we built a beautiful HTML5 user interface for uploading, resizing, and selecting a poster image for our videos. Now, we’re diving into the essential part: the backend.

This post focuses on using PHP to handle the file uploads, manage video metadata using MariaDB, and secure the system with CRUD operations (Create, Read, Update, Delete).

The Backend Architecture

Our backend needs to perform three core tasks:

  1. Receive the video file, poster image, and metadata from the Fetch API request.
  2. Securely save the video and image files in a dedicated folder outside of the main web root.
  3. Store the video’s information (like the file path, user ID, and dimensions) in a MariaDB database.

1. Setting Up the Database (MariaDB)

We need a simple table to store the details about each uploaded video. This allows us to easily retrieve, update, or delete records.

SQL Code:

CREATE TABLE video_uploads (
    video_id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    file_name VARCHAR(255) NOT NULL,
    file_path VARCHAR(255) NOT NULL,
    poster_path VARCHAR(255) NOT NULL,
    width INT,
    height INT,
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

2. The PHP Endpoint and File Handling

Remember the endpoint we defined in Part 1? /wp-json/my-video-plugin/v1/upload. Your PHP code will live behind this URL. The script below illustrates the core logic for receiving the files via the POST request and moving them to a secure location.

PHP Upload Script:

// Define a secure storage location outside the main public web folder
$uploadDir = '/home/user/secure_video_storage/'; 

// 1. Check if files were sent
if (!isset($_FILES['video']) || !isset($_FILES['poster'])) {
    http_response_code(400); // Bad Request
    echo json_encode(['message' => 'Missing video or poster file.']);
    exit;
}

$videoFile = $_FILES['video'];
$posterFile = $_FILES['poster'];

// Generate a unique filename to prevent clashes
$uniqueId = uniqid();
$videoFilename = $uniqueId . "_" . basename($videoFile['name']);
$posterFilename = $uniqueId . "_poster.jpg";

$videoPath = $uploadDir . $videoFilename;
$posterPath = $uploadDir . $posterFilename;

// 2. Move the uploaded files to the secure directory
if (move_uploaded_file($videoFile['tmp_name'], $videoPath) && 
    move_uploaded_file($posterFile['tmp_name'], $posterPath)) {
    
    // Files are saved, now handle MariaDB insertion...
    
    // (Database connection and sanitization code would go here)
    $db = new PDO("mysql:host=localhost;dbname=your_db_name", "user", "pass");
    
    // Get metadata from the Fetch API
    $width = $_POST['width'] ?? 0;
    $height = $_POST['height'] ?? 0;
    $userId = 1; // Example user ID

    // 3. INSERT (Create) the record into MariaDB
    $stmt = $db->prepare("INSERT INTO video_uploads 
                         (user_id, file_name, file_path, poster_path, width, height) 
                         VALUES (?, ?, ?, ?, ?, ?)");
    
    $stmt->execute([$userId, $videoFilename, $videoPath, $posterPath, $width, $height]);

    http_response_code(201); // Created
    echo json_encode(['message' => 'Video uploaded and metadata saved successfully!', 'id' => $db->lastInsertId()]);

} else {
    http_response_code(500); // Server Error
    echo json_encode(['message' => 'Failed to move uploaded files. Check folder permissions.']);
}

3. Handling CRUD Operations (Replace/Delete)

A complete system must handle the full lifecycle of a video:

  • Replace (Update): User uploads a new video/poster for an existing ID. You must use an UPDATE SQL statement on the video_uploads table. Crucially, you must first use PHP’s unlink() function to **delete the old video and poster files** from the secure folder to save disk space.
  • Delete: User removes the video entirely. Execute a SQL DELETE query against the video_uploads table, then use PHP’s unlink() function to **permanently delete the files** from the disk using the file path stored in the database.

Screenshots and Screencast

Video File Upload Code
Gnome Text Editor Displaying Fetch URL For Video Upload HTML Code

Video File Upload Handler
Gnome Text Editor Displaying PHP Video Upload Code

PHPMyAdmin Database Query
Web Browser Displaying PHPMyAdmin Database Table Creation Query

Video File Upload Form
Web Browser Displaying A Drag And Drop Video Upload Form

Video Preview, Resize And Thumbnail
Web Browser Displaying Video Preview With Resize And Thumbnail Scrubber Options

Video File Upload Failure
Web Browser Displaying A Failed Video File Upload

Uploaded Video Path In Database
Web Browser Running PHPMyAdmin Displaying A List Of Uploaded Videos

PHP Video File Upload AJAX Video

Keep Learning PHP and Backends

Ready to take your PHP and backend development skills to the next level?

If you need personalized guidance on your coding journey, including PHP, or require help with **updating or migrating existing frameworks**, I’m available for **one-on-one programming tutorials**. Feel free to reach out and schedule a session: https://ojambo.com/contact.

Recommended Resources:

Disclosure: Some of the links above are referral (affiliate) links. I may earn a commission if you purchase through them - at no extra cost to you.

About Edward

Edward is a software engineer, web developer, and author dedicated to helping people achieve their personal and professional goals through actionable advice and real-world tools.

As the author of impactful books including Learning JavaScript, Learning Python, Learning PHP, Mastering Blender Python API, and fiction The Algorithmic Serpent, Edward writes with a focus on personal growth, entrepreneurship, and practical success strategies. His work is designed to guide, motivate, and empower.

In addition to writing, Edward offers professional "full-stack development," "database design," "1-on-1 tutoring," "consulting sessions,", tailored to help you take the next step. Whether you are launching a business, developing a brand, or leveling up your mindset, Edward will be there to support you.

Edward also offers online courses designed to deepen your learning and accelerate your progress. Explore the programming on languages like JavaScript, Python and PHP to find the perfect fit for your journey.

📚 Explore His Books – Visit the Book Shop to grab your copies today.
💼 Need Support? – Learn more about Services and the ways to benefit from his expertise.
🎓 Ready to Learn? – Check out his Online Courses to turn your ideas into results.

Leave a Reply

Your email address will not be published. Required fields are marked *