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.