PHP上传图片时修改文件名(保留扩展名)问题求助
Hey, I get it — you’re so close! The problem is that when you swapped $filename for $currentName, you dropped the original file extension entirely. That’s why the upload stopped working (or the file became unrecognizable) — the server has no clue what type of file it’s dealing with anymore.
Luckily, you already have the extension stored in the $ext variable from this line:
$ext = pathinfo($filename, PATHINFO_EXTENSION);
All you need to do is combine $currentName with this extension to create a valid, recognizable filename. Here’s the key fix for the move_uploaded_file line:
move_uploaded_file($_FILES["photo"]["tmp_name"], "img/profile_pictures/" . $currentName . "." . $ext);
This way, the file will be named something like 123.jpg (if $currentName is "123" and the original file was a JPG) instead of just 123 with no extension.
Full Modified Code
Here’s your updated code with the fix applied, plus a couple of small robustness improvements:
<?php $currentName = $_SESSION["uID"]; // Check if form was submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Check if file was uploaded without errors if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){ $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png"); $filename = $_FILES["photo"]["name"]; $filetype = $_FILES["photo"]["type"]; $filesize = $_FILES["photo"]["size"]; // Verify file extension $ext = pathinfo($filename, PATHINFO_EXTENSION); if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format."); // Verify file size - 5MB maximum $maxsize = 5 * 1024 * 1024; if($filesize > $maxsize) die("Error: File size is larger than the allowed limit."); // Verify MIME type if(in_array($filetype, $allowed)){ // ** Fixed line here: Combine user ID with original extension ** $newFilename = $currentName . "." . $ext; $uploadPath = "img/profile_pictures/" . $newFilename; if(move_uploaded_file($_FILES["photo"]["tmp_name"], $uploadPath)){ // Redirect back to referrer on success header("Location: " . $_SERVER['HTTP_REFERER']); exit; } else { echo "Error: There was a problem uploading your file. Please try again."; } } else{ echo "Error: There was a problem uploading your file. Please try again."; } } else{ echo "Error: " . $_FILES["photo"]["error"]; } } ?>
Quick Notes:
- Permissions: Make sure the
img/profile_pictures/directory has write permissions for the web server (usuallychmod 755orchmod 775depending on your hosting setup). - Overwriting Files: If a user uploads another photo later, this code will overwrite their existing profile picture. That’s probably intentional for a profile photo, but if you want to avoid overwrites, you could add a timestamp or unique suffix to the filename.
- Case Sensitivity: Some servers treat
.JPGand.jpgas different extensions. If you want to standardize, convert the extension to lowercase withstrtolower($ext).
内容的提问来源于stack exchange,提问作者Erik Auranaune

