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

如何修改W3Schools的PHP上传脚本以唯一ID命名上传文件

How to Save Uploaded Files with a Unique ID Instead of Original Filename in PHP

Hey there! I’ve helped tons of folks tweak that W3Schools upload script to use unique filenames—let’s get yours sorted out. The core issue is replacing the original filename with a unique identifier so you don’t end up overwriting files when two users upload something with the same name.

The Fix: Replace the Original Filename with a Unique ID

Here’s how to modify your existing script. We’ll keep the file extension (so your system/browser recognizes the file type) but swap out the original name for a unique string.

Step 1: Replace the Target File Line

Your original code uses the uploaded file’s original name:

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

Replace that with code that generates a unique ID and appends the original extension:

// Generate a unique ID (uses current time in microseconds for uniqueness)
// Adding a prefix like 'upload_' makes it easier to identify later
$unique_id = uniqid('upload_', true);

// Grab the original file's extension (jpg, png, pdf, etc.)
$file_extension = strtolower(pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION));

// Combine the directory, unique ID, and extension to make the final file path
$target_file = $target_dir . $unique_id . '.' . $file_extension;

Step 2: Full Modified Script

Here’s the complete updated upload.php with the unique filename logic included:

<?php
$target_dir = "uploads/";

// Generate unique filename
$unique_id = uniqid('upload_', true);
$file_extension = strtolower(pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION));
$target_file = $target_dir . $unique_id . '.' . $file_extension;

$uploadOk = 1;
$imageFileType = $file_extension; // Reuse the extension we already grabbed

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists (now redundant with unique IDs, but you can keep it just in case)
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size (adjust as needed)
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded as " . $unique_id . "." . $file_extension;
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Extra Tips for Even Better Uniqueness

If you want an extra layer of randomness (to eliminate the tiny chance of duplicate IDs), you can use random_bytes() instead of uniqid():

// Generates a 32-character random string (super unique)
$unique_id = bin2hex(random_bytes(16));

Important Notes

  • Make sure your uploads/ directory has write permissions (usually set to 755 or 775 via FTP or your hosting control panel).
  • If you need to track which user uploaded which file, you can store the unique ID and original filename in a database alongside the user’s info.

内容的提问来源于stack exchange,提问作者40oz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:25:17