PHP图片上传异常:提示成功但文件未存入uploads文件夹
Hey Ethan, let's troubleshoot why your uploaded image isn't showing up in the uploads folder even though you get a "Success" message. Here are the key bugs in your code and how to fix them:
1. Mismatched File Input Name
Your form uses <input type="file" name="profileImage">, but in your PHP code you're referencing $_FILES['file'] everywhere. This means you're not actually accessing the uploaded file data at all. Replace all instances of $_FILES['file'] with $_FILES['profileImage'].
2. Wrong Variable Interpolation
When splitting the file extension, you used single quotes around $fileName:
$fileExt = explode('.', '$fileName');
Single quotes treat the text as a literal string, so you're splitting the string '$fileName' instead of the actual filename. Remove the quotes:
$fileExt = explode('.', $fileName);
3. Reversed move_uploaded_file Parameters
The move_uploaded_file function requires the temporary file path as the first argument, and the destination path as the second. You had them backwards:
// Wrong move_uploaded_file($fileNameNew, $fileDestination); // Correct move_uploaded_file($fileTmpName, $fileDestination);
4. Invalid uniqid Parameter
The second parameter for uniqid() is a boolean, but you passed a string 'true'. Change it to the boolean true:
$fileNameNew = uniqid('', true).".".$fileActualExt;
5. Unrealistic File Size Limit
Your current limit is $fileSize > 2000 (only 2KB), which is way too small for most images. Update it to a reasonable size, like 2MB:
elseif($fileSize > 2 * 1024 * 1024){ // 2MB in bytes echo "File is too big! Maximum size is 2MB."; }
Fixed PHP Code
if(isset($_POST['uploadImage'])){ $file = $_FILES['profileImage']; $fileName = $_FILES['profileImage']['name']; $fileTmpName = $_FILES['profileImage']['tmp_name']; $fileSize = $_FILES['profileImage']['size']; $fileError = $_FILES['profileImage']['error']; $fileType = $_FILES['profileImage']['type']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allowed = array('png', 'jpg', 'jpeg', 'PNG', 'JPG', 'JPEG'); if(!$fileError == 0){ echo "There was an error uploading this image!"; } elseif($fileSize > 2 * 1024 * 1024){ echo "File is too big! Maximum size is 2MB."; } else{ $fileNameNew = uniqid('', true).".".$fileActualExt; $fileDestination = "uploads/".$fileNameNew; move_uploaded_file($fileTmpName, $fileDestination); echo "Success"; } }
Fixed Form Code
Add proper closing structure for clarity:
<form action="my-account.php" method="post" enctype="multipart/form-data"> Upload a profile image: <input type="file" name="profileImage"><br> <input type="submit" name="uploadImage" value="Upload"> </form>
Final Checks
- Make sure the
uploadsfolder exists in the same directory asmy-account.php. - Ensure the
uploadsfolder has write permissions (set to755or777depending on your server configuration).
内容的提问来源于stack exchange,提问作者Ethan

