PHP File Upload
PHP file upload code: a script that gives a new name to an uploaded file if the name already exists.
PHP Code to Increment Filename if already exists
When a user uploads a file with a name that already exists in the folder, PHP can replace the old file, and you lose it. Here we keep both files: if photo.jpg exists, the new file is saved as photo-1.jpg, then photo-2.jpg, and so on.
Solution
We write a function that takes the folder and the file name. It checks with file_exists() and adds a counter to the name until it finds a name that is free.
<?php
function uniqueFileName(string $dir, string $name): string
{
$info = pathinfo($name);
$base = $info["filename"];
$ext = isset($info["extension"]) ? "." . $info["extension"] : "";
$newName = $name;
$i = 1;
while (file_exists($dir . "/" . $newName)) {
$newName = $base . "-" . $i . $ext;
$i++;
}
return $newName;
}
// Suppose the folder "uploads" already has photo.jpg and photo-1.jpg
echo uniqueFileName("uploads", "photo.jpg") . "<br>";
echo uniqueFileName("uploads", "notes.pdf");
?>
Output:
photo-2.jpg
notes.pdf
How it works
pathinfo()splits the name into the base (photo) and the extension (jpg).- The
whileloop checks the name again and again. Every time the file exists, it makes a new name with the next number. - When no file has that name, the loop stops and the free name is returned.
Use it in a file upload form
This is a complete upload page. It checks the upload error, the real file type and the size, and cleans the file name before it uses the function.
<?php
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["file"])) {
$dir = __DIR__ . "/files";
if ($_FILES["file"]["error"] !== UPLOAD_ERR_OK) {
$message = "Upload failed.";
} else {
$allowed = ["image/jpeg", "image/png", "application/pdf"];
$mime = (new finfo(FILEINFO_MIME_TYPE))->file($_FILES["file"]["tmp_name"]);
if (!in_array($mime, $allowed, true)) {
$message = "Only JPG, PNG and PDF files are allowed.";
} elseif ($_FILES["file"]["size"] > 2 * 1024 * 1024) {
$message = "File is too big. Maximum 2 MB.";
} else {
// Keep only safe characters in the file name
$clean = preg_replace("/[^A-Za-z0-9._-]/", "_", basename($_FILES["file"]["name"]));
$final = uniqueFileName($dir, $clean);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $dir . "/" . $final)) {
$message = "File uploaded as: " . htmlspecialchars($final);
} else {
$message = "Could not save the file.";
}
}
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
<p><?php echo $message; ?></p>
Important points:
- Create the
filesfolder first and give PHP permission to write in it. - If the upload fails, print
error_get_last()while testing to see the reason. - Two users can upload the same name at the same moment, and both can get the same free name. If this can happen on your website, use a random name instead, like
bin2hex(random_bytes(16)).
Read the basics in PHP File Upload and the safety rules in how to upload a file securely in PHP.