Keywords: PHP | File Upload | Video | Database | Web Security
Abstract: This article provides a comprehensive tutorial on implementing video file uploads in PHP, covering HTML form setup, server-side processing with error handling and security checks, moving files to organized folders, and logging details in a MySQL database. It includes rewritten code examples and discusses file system permissions for web servers.
Introduction
File upload functionality is essential in modern web applications, enabling users to share media such as videos. This guide explains how to build a secure system using PHP for uploading video files, organizing them into folders based on categories like courses, and recording upload information in a database for tracking purposes. By following step-by-step instructions and incorporating security best practices, developers can create robust upload features that handle user inputs safely.
HTML Form Setup
To initiate file uploads, an HTML form must include the enctype="multipart/form-data" attribute, which allows the transmission of binary data. Below is a sample form that collects the user's name, email, video file, and course selection, enhancing usability with validation attributes.
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required>
<br>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required>
<br>
<label for="file">Video File:</label>
<input type="file" name="file" id="file" accept="video/*" required>
<br>
<label for="course">Course:</label>
<select name="course" id="course">
<option value="java">Java</option>
<option value="python">Python</option>
<option value="vb">Visual Basic</option>
<option value="c">C/C++</option>
<option value="ruby">Ruby</option>
</select>
<br>
<input type="submit" name="submit" value="Upload">
</form>In this form, the accept="video/*" attribute limits file selection to video types, while the required attribute ensures that all fields are completed before submission, reducing user errors.
PHP Upload Handler
The server-side PHP script processes the uploaded file by checking for errors, validating the file type and size, and moving it to a designated folder. Here is an enhanced version that incorporates security measures and database integration.
<?php
// Define allowed file extensions and maximum file size
$allowedExts = array("mp4", "avi", "mov", "wmv");
$maxFileSize = 50 * 1024 * 1024; // 50 MB in bytes
// Retrieve file information from the global $_FILES array
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// Check for upload errors using constants like UPLOAD_ERR_OK
if ($fileError !== UPLOAD_ERR_OK) {
die("Upload error: " . $fileError);
}
// Validate file extension against the allowed list
if (!in_array($fileExt, $allowedExts)) {
die("Invalid file type. Allowed types: " . implode(", ", $allowedExts));
}
// Validate file size to prevent oversized uploads
if ($fileSize > $maxFileSize) {
die("File too large. Maximum size: " . ($maxFileSize / (1024 * 1024)) . " MB");
}
// Define upload folder based on the selected course
$course = $_POST['course'];
$uploadDir = "uploads/" . $course . "/";
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true); // Create directory recursively if it does not exist
}
// Generate a unique filename to avoid conflicts and enhance security
$safeFileName = uniqid() . '.' . $fileExt;
$destination = $uploadDir . $safeFileName;
// Move the uploaded file from temporary location to the destination
if (move_uploaded_file($fileTmpName, $destination)) {
echo "File uploaded successfully to: " . $destination;
// Proceed to database entry after successful file move
} else {
die("Failed to move uploaded file.");
}
// Database integration using PDO for secure operations
$host = 'localhost';
$dbname = 'upload_db';
$username = 'root';
$password = 'password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL statement with named parameters to prevent SQL injection
$sql = "INSERT INTO uploads_log (user_name, user_email, file_name, file_size, course, upload_ip, upload_date) VALUES (:name, :email, :filename, :size, :course, :ip, NOW())";
$stmt = $pdo->prepare($sql);
// Bind parameters from the form inputs and server variables
$stmt->bindParam(':name', $_POST['name']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':filename', $safeFileName);
$stmt->bindParam(':size', $fileSize);
$stmt->bindParam(':course', $course);
$stmt->bindParam(':ip', $_SERVER['REMOTE_ADDR']);
// Execute the statement and confirm success
$stmt->execute();
echo "Database entry added successfully.";
} catch (PDOException $e) {
die("Database error: " . $e->getMessage());
}
?>This script employs PDO for database interactions to mitigate SQL injection risks and logs user details, file attributes, and IP address into a MySQL table, ensuring traceability.
Security Considerations
Handling file uploads requires stringent security measures to prevent vulnerabilities such as malware uploads or data breaches. Key practices include validating file types using both extensions and MIME types, imposing size limits to avoid denial-of-service attacks, utilizing move_uploaded_file() for secure file relocation, storing files outside the web root directory, and sanitizing user inputs to counter cross-site scripting (XSS). Additionally, implementing error handling for various upload scenarios enhances robustness.
File System Permissions
Proper file permissions are critical for maintaining security on web servers. As highlighted in reference materials, setting appropriate ownership and access rights prevents unauthorized access. For instance, on a Linux system with Apache, assign the upload directory to the web server user (e.g., www-data) and configure permissions to allow necessary read/write operations while restricting others.
sudo chown -R www-data:www-data /var/www/html/uploads
sudo chmod -R 755 /var/www/html/uploadsThese commands ensure that the web server can write files securely, and applying the setgid bit (chmod g+s) maintains consistent group ownership for new files, reducing permission-related issues.
Conclusion
Implementing a video file upload system in PHP involves meticulous attention to form design, server-side validation, and database integration. By adhering to security protocols and configuring file permissions correctly, developers can build efficient and safe applications that manage user uploads effectively. This approach not only facilitates organized file storage but also enables reliable tracking through database logs.