技术问询:如何为上传图片的文件名添加三位随机数前缀
Fixing Your PHP File Upload with 3-Digit Random Prefix
Got it, let's get this working properly. Here are the key issues in your current code and how to fix them:
- You generated the
$randomvariable but never used it when renaming the file rand(000,999)doesn’t produce 3-digit numbers with leading zeros (it just generates integers from 0 to 999, so numbers like 7 become "7" instead of "007")
Here's the revised code with both issues resolved, plus some best practice tweaks:
if(isset($_POST['submit']) && $_POST['submit'] !== ""){ $name = $_FILES['photo']['name']; $size = $_FILES['photo']['size']; $type = $_FILES['photo']['type']; $temp = $_FILES['photo']['tmp_name']; // Generate a 3-digit random number with leading zeros (000-999) $random = sprintf('%03d', rand(0, 999)); // Create new filename: random prefix + original name (underscore for clarity) $new_filename = $random . '_' . $name; $date = date('Y-m-d H:i:s'); // First verify the file move succeeds before updating the database if(move_uploaded_file($temp, "files/" . $new_filename)){ // Use prepared statement to avoid SQL injection (critical security fix!) $stmt = $DBcon->prepare("INSERT INTO upload (name, date) VALUES (:filename, :date)"); $stmt->bindParam(':filename', $new_filename); $stmt->bindParam(':date', $date); if($stmt->execute()){ header("location:index.php"); exit; // Always exit after redirect to stop further code execution } else{ die("Database error: " . implode(", ", $DBcon->errorInfo())); } } else { die("Failed to move uploaded file. Check directory permissions or path."); } }
Key Changes Explained:
- Proper 3-Digit Random Prefix:
sprintf('%03d', rand(0, 999))ensures every number is 3 digits—even ifrand()returns 5, it becomes "005". - Use the Random Prefix: We combine the random number with the original filename (using an underscore to keep things readable) and use this new name everywhere: when moving the file and inserting into the database.
- Security Fix: Swapped direct SQL insertion for a prepared statement to eliminate SQL injection risks (never trust user-provided data like filenames in raw queries!).
- Better Error Handling: Added checks for file move success, and used PDO's error handling instead of outdated
mysql_error()(since you're using$DBconwhich looks like a PDO connection). - Exit After Redirect: Prevents leftover code from running after sending the redirect header, which is a standard best practice.
内容的提问来源于stack exchange,提问作者Marko Hirsch
相关产品推荐
相关产品推荐

