PHP文件上传功能失效问题求助
Alright, let's break down why your upload script is always failing and fix it step by step. Your upload.inc.php has a couple of critical bugs, plus a few other things to verify even after fixing the code.
1. Case-Sensitive Variable Name Mistake
PHP treats variables as case-sensitive, and you’ve got a typo here:
- You define
$tempName = basename($_FILES["fileToUpload"]['tmp_name']);(capital N) - But then you try to use
$temp_name(lowercase n) inmove_uploaded_file
Since $temp_name is never defined, the function gets an invalid path to the temporary upload file—this alone would cause the move to fail.
2. Duplicate move_uploaded_file Call
You’re calling the move function twice in a row:
move_uploaded_file($temp_name, "$uploadsDir/$name"); if(move_uploaded_file($temp_name, "$uploadsDir/$name")) {
The first call already moves the temporary file to your uploads directory. By the time the second call runs, the temporary file no longer exists on the server—so it will always return false and trigger your error message.
Fixed upload.inc.php Code
Here’s the corrected version with extra safeguards:
<?php if(isset($_POST['submit'])) { $uploadsDir = '../uploads/'; // Make sure the uploads directory exists (create it if not) if (!is_dir($uploadsDir)) { mkdir($uploadsDir, 0755, true); // Recursive create, 0755 is safer than 777 } $name = uniqid() . '_' . basename($_FILES["fileToUpload"]["name"]); // Avoid filename conflicts $tempName = $_FILES["fileToUpload"]['tmp_name']; // No need for basename—tmp_name is a full path $error = $_FILES['fileToUpload']['error']; if ($error > 0) { echo "Error: " . $error . "<br />"; } else { // Only call move_uploaded_file once if(move_uploaded_file($tempName, $uploadsDir . $name)) { echo "Successful"; echo "Upload: " . $name . "<br />"; echo "Stored in: Uploads Directory!"; } else { echo "Did not move files!<br />"; // Add debug info to see the exact error echo "Debug Details: " . error_get_last()['message']; } } } ?>
Extra Checks to Rule Out Other Issues
- Directory Permissions: Skip using
777(it’s a security risk)—set your uploads directory to0755instead. Double-check that the server’s web process (likewww-datafor Apache ornginxfor Nginx) has write access to the directory, not just "all users". - PHP Upload Limits: Verify your
php.inisettings:file_uploads = On(file uploads are enabled)upload_max_filesizeis large enough for your filespost_max_sizeis larger thanupload_max_filesize
- Filename Conflicts: The added
uniqid()prefix ensures you don’t overwrite existing files with the same name, which would also causemove_uploaded_fileto fail.
内容的提问来源于stack exchange,提问作者James

