You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP文件上传失败求助:HTML与PHP均用name="file"却无效

Troubleshooting Your PHP File Upload Issue

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 to 755 works (or 777 temporarily for testing, though 755 is more secure).
  • PHP Configuration Limits: Check your php.ini file for these settings:
    • upload_max_filesize: Ensure it’s large enough for your files
    • post_max_size: Should be larger than upload_max_filesize
    • max_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:59:29