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:
- Receive the video file, poster image, and metadata from the Fetch API request.
- Securely save the video and image files in a dedicated folder outside of the main web root.
- 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
UPDATESQL statement on thevideo_uploadstable. Crucially, you must first use PHP’sunlink()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
DELETEquery against thevideo_uploadstable, then use PHP’sunlink()function to **permanently delete the files** from the disk using the file path stored in the database.
Screenshots and Screencast







Keep Learning PHP and Backends
Ready to take your PHP and backend development skills to the next level?
- Check out my book, “Learning PHP Programming” on Amazon: https://www.amazon.com/Learning-PHP-Programming-Edward-Ojambo-ebook/dp/B0D442PR8T.
- For a comprehensive, guided educational experience, consider the related course, **”Learning PHP”**: https://ojamboshop.com/product/learning-php.
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.
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.