PHP文件上传失败求助:HTML与PHP均用name="file"却无效
Hey there, let's figure out why your file upload isn't working— I’ve spotted a few key issues in your code that are likely causing the problem:
1. The Form Isn’t Actually Submitting!
Look at your submit button’s onClick handler:
<button type="submit" id="register-btn" onClick="register();return false;" ...>Submit</button>
The return false; here blocks the form’s default submit behavior. Even if you click the button, the form never sends data (including your file) to welcome.php.
Fix:
Either remove the return false; entirely, or modify your register() function to return true only when validation passes (so the form submits when it should):
<button type="submit" id="register-btn" onClick="return register();" ...>Submit</button>
(Make sure your register() function returns a boolean value based on validation success.)
2. Your PHP Code Doesn’t Save the Uploaded File
Right now, your PHP only checks if the file already exists—but it never actually moves the uploaded file from the server’s temporary directory to your uploads/ folder.
Fix:
Add the move_uploaded_file() function after your checks. Here’s an updated version of your PHP code:
<?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES['file']["name"]); $uploadOk = 1; $fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // If all checks pass, move the file if ($uploadOk == 1) { if (move_uploaded_file($_FILES['file']["tmp_name"], $target_file)) { echo "The file ". htmlspecialchars( basename( $_FILES['file']["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?>
3. Additional Checks to Rule Out Other Issues
- Directory Permissions: Make sure your
uploads/folder has write permissions for the web server. On most systems, setting permissions to755works (or777temporarily for testing, though755is more secure). - PHP Configuration Limits: Check your
php.inifile for these settings:upload_max_filesize: Ensure it’s large enough for your filespost_max_size: Should be larger thanupload_max_filesizemax_execution_time: Might need to increase if uploading large files
- Debugging Tip: Add
var_dump($_FILES);at the top of your PHP script to see if the file data is even being received. If it’s empty, that confirms the form isn’t submitting correctly.
内容的提问来源于stack exchange,提问作者Salman Ashraf

