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 theuploads/directory for all files starting withprofile{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. Theis_file()check ensures we don't accidentally try to delete directories. exitAfter 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
pdffrom the$allowedarray 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
相关产品推荐
相关产品推荐

