View Full Version : File upload duplicate naming question

09-10-2009, 08:46 AM
I am working on a script that will allow the user to upload images to the server. Easy enough. But what I am trying to do is add in a layer of protection to prevent overwriting a file (bike.jpg) with the same name by appending _2 (bike_2.jpg). I know I want to check to see if the file already exist:

if (file_exist($filename)) {
//do something

And if it does I want to append _2 to the name. But I also want to check to see if there is already that file as well (bike_2.jpg) and if there is get the last number and increment by (bike_3.jpg).

I am looking for some help with this so really anything would be great.

I thought there would already be something online that would do this sort of thing that I could pick apart and see how it's done so I could rebuild my own. But I came up empty handed. Any links are welcome.

Thanks in advance.

09-10-2009, 09:37 AM
$file = 'bike_1200';
$ex = explode("_", $file);
$newfile = $ex[0] . '_' . ($ex[1] + 1);

This results in bike_1201

Simble, right? :)

09-10-2009, 05:50 PM
Thanks Zangeel,

That is great and exactly what I was looking forward. As for taking the original file name (bike_1200.jpg) and removing the file extension (.jpg) to then run the code you previously showed. I'm thinking that would be done with something like


09-10-2009, 08:16 PM
Ah, forgot about the file extension, preg_split will just take out the number or whatever the regex matches. So here's how I did it

$file = "bike_1.jpg";
$n = preg_split("/_[0-9]{1,}/", $file);
$x = preg_match("/_[0-9]{1,}/", $file, $numb);
$newFile = $n[0] . '_' . (str_replace('_', '', $numb[0]) + 1) . $n[1];
echo $newFile;

So basically all you have to do now is make sure they dont upload a filename with a underscore in it, and make sure the new file name has _1 after it and this script should work fine.