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

PHP上传图片时修改文件名(保留扩展名)问题求助

Fix: Rename Uploaded Image to User ID with Original Extension

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 (usually chmod 755 or chmod 775 depending 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 .JPG and .jpg as different extensions. If you want to standardize, convert the extension to lowercase with strtolower($ext).

内容的提问来源于stack exchange,提问作者Erik Auranaune

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:57:36