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

PHP & MySQL:文件名(不含扩展名)相同时替换图片的实现

Fixing Avatar Replacement (Regardless of File Extension)

Hey there! I see you want new avatar uploads to replace the old ones even when the file extensions differ—totally makes sense for a profile image system. Let's adjust your code to make that happen.

The core issue with your current code is that it creates a new file with the current extension (e.g., profile1.png instead of overwriting profile1.jpg). To fix this, we need to:

  • Find all existing profile files for the user (matching the profile{id} prefix, no matter the extension)
  • Delete those old files before saving the new one

Here's the updated code with these changes:

if (isset($_POST['submit'])) {
    $file = $_FILES['file'];
    $fileName = $_FILES['file']['name'];
    $fileTmpName = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileType = $_FILES['file']['type'];
    $fileError = $_FILES['file']['error'];
    
    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));
    $allowed = array('jpg', 'jpeg', 'png', 'pdf'); // Quick note: PDF for avatars? Maybe remove this if it's not intended!

    if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
            if ($fileSize < 1000000) {
                // Define base filename (without extension) and upload directory
                $baseFileName = "profile".$id;
                $uploadDir = 'uploads/';
                
                // Step 1: Delete all old profile files for this user
                $oldFiles = glob($uploadDir . $baseFileName . '.*');
                if ($oldFiles !== false) {
                    foreach ($oldFiles as $oldFile) {
                        // Ensure we're only deleting files, not directories
                        if (is_file($oldFile)) {
                            unlink($oldFile);
                        }
                    }
                }
                
                // Step 2: Save the new avatar file
                $fileNameNew = $baseFileName . "." . $fileActualExt;
                $fileDestination = $uploadDir . $fileNameNew;
                move_uploaded_file($fileTmpName, $fileDestination);
                
                // Update database to reflect the new avatar
                $sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
                $result = mysqli_query($conn, $sql);
                
                header("Location:index.php?upload=success");
                exit; // Always exit after a header redirect to stop extra code from running
            } else {
                echo "File too large!";
            }
        } else {
            echo "Error uploading your file!";
        }
    } else {
        echo "Format not allowed!";
    }
}

Key Changes Explained:

  • glob() Function: This scans the uploads/ directory for all files starting with profile{id}. (any extension), returning an array of matching file paths.
  • Old File Cleanup: We loop through the matched files and use unlink() to delete each one. The is_file() check ensures we don't accidentally try to delete directories.
  • exit After Redirect: A small but important best practice—this prevents any leftover code from executing after sending the redirect header.
  • PDF Allowance: I noticed you included PDF in allowed formats. If this is strictly for profile images, you'll probably want to remove pdf from the $allowed array to avoid non-image uploads.

Just a quick heads-up: Make sure your uploads/ directory has proper write permissions so the server can delete old files and save new ones without issues.

内容的提问来源于stack exchange,提问作者J Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:10:24