So I am trying to upload some images to a folder on my server with the script below,but it saves every image as \"image.jpg\" and it overwrites the last uploaded image if I
You can implement something like Windows's auto-file-renaming:
$try = 1;
while($file_exists($target_file)) {
$target_file = preg_replace('/(\(\\d+\))*(\.[^\\(\\)]+)$/',
"({$try})\\2", $target_file);
$try++;
}
This will replace the file "duplicate.jpg" with "duplicate(1).jpg", then "duplicate(2).jpg", and so on.
It will still be prone to unlikely race conditions, just as using uniqid()
or microtime()
(which, conflict-wise, are both better).
Otherwise, always use tempnam()
. You can check out this answer.
A simple way to get a unique filename is to get the current Unix time in milliseconds and append (or prepend) that to the filename. The command to use is microtime()
.
For example:
$target_file = $target_dir . microtime() . basename($_FILES["fileToUpload"]["name"]);
You could also try things like hashing the file to get a unique hash with low probability of collisions, but this is faster and just as effective.