使用PHP上传视频失败,请求帮忙修正问题代码
Fixing Your PHP Video Upload Code
Hey there! Let's break down what's wrong with your code and fix it step by step—PHP file uploads have a few gotchas, especially if you're new to it.
What's Wrong with the Original Code?
Let's go over the key issues:
- Outdated MySQL functions:
mysql_*was deprecated years ago and removed in modern PHP. It's insecure and won't work on newer servers. - Variable typos & mix-ups: You overwrote
$namewith$_FILES['file']['temp_name'](it's supposed to betmp_name), and never defined the$tempvariable used inmove_uploaded_file. - No upload error checking: You didn't verify if the file actually uploaded successfully (e.g., user forgot to select a file, file was too big).
- SQL injection risk: Inserting raw filenames directly into your database query is a major security hole.
- No directory validation: If the
uploaded/folder doesn't exist, the file can't be saved. - Duplicate filename issues: If two users upload files with the same name, the older one gets overwritten.
Corrected Code with Explanations
Here's a fixed version of your code with safety checks and best practices:
<?php // Use mysqli (supported, secure) instead of deprecated mysql_* functions $conn = mysqli_connect("localhost", "root", "123456789", "vid"); // Check if database connection failed if (!$conn) { die("Database connection failed: " . mysqli_connect_error()); } // Define upload directory and create it if it doesn't exist $uploadDir = 'uploaded/'; if (!is_dir($uploadDir)) { mkdir($uploadDir, 0755, true); // Create folder with proper read/write permissions } if (isset($_POST['submit'])) { // First, check if the file uploaded without errors if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { $originalFilename = $_FILES['file']['name']; $tempFilepath = $_FILES['file']['tmp_name']; // Generate a unique filename to avoid overwriting existing files $uniqueFilename = uniqid() . '_' . $originalFilename; $destination = $uploadDir . $uniqueFilename; // Move the uploaded file to our target directory if (move_uploaded_file($tempFilepath, $destination)) { $videoUrl = "http://localhost/video/" . $destination; // Use prepared statements to prevent SQL injection $stmt = mysqli_prepare($conn, "INSERT INTO `videos` (`name`, `url`) VALUES (?, ?)"); mysqli_stmt_bind_param($stmt, "ss", $originalFilename, $videoUrl); if (mysqli_stmt_execute($stmt)) { echo "Video uploaded and saved to database successfully!"; } else { echo "Failed to save to database: " . mysqli_error($conn); } mysqli_stmt_close($stmt); } else { echo "Error: Could not move the uploaded file."; } } else { // Handle common upload errors with clear messages switch ($_FILES['file']['error']) { case UPLOAD_ERR_INI_SIZE: echo "Error: File exceeds maximum size allowed by server (check php.ini)"; break; case UPLOAD_ERR_FORM_SIZE: echo "Error: File exceeds maximum size specified in the upload form"; break; case UPLOAD_ERR_PARTIAL: echo "Error: File was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: echo "Error: No file was selected for upload"; break; default: echo "Unknown upload error: " . $_FILES['file']['error']; } } } // Close the database connection when done mysqli_close($conn); ?>
Key Improvements Explained
- Mysqli Database Connection: Uses modern, supported functions and adds error checking so you know if the database connection fails.
- Directory Validation: Automatically creates the
uploaded/folder if it doesn't exist, with correct permissions. - Upload Error Handling: Catches common issues like missing files, oversized files, and partial uploads with clear error messages.
- Unique Filenames: Uses
uniqid()to generate a unique prefix for each uploaded file, preventing overwrites. - Prepared Statements: Safely inserts data into the database without risking SQL injection (no more raw user input in queries).
- Clear Feedback: Tells you exactly what went wrong if something fails, making debugging easier.
Extra Tips for Production
- Restrict File Types: Add checks to only allow video files (e.g.,
.mp4,.mov) by verifying the file extension or MIME type. - Limit File Sizes: Ensure your
php.inisettings (upload_max_filesize,post_max_size) are set to handle your video files. - Secure Permissions: Double-check that the
uploaded/folder has write permissions for PHP, but not too open (0755 is a safe default).
内容的提问来源于stack exchange,提问作者Akash Gormani
相关产品推荐
相关产品推荐

