Take the 2-minute tour ×

I have a file input known as 'name=fileImage'. Now I have php code below where it checks to see if file exists in the folder (ImageFiles) or not:

if (file_exists("ImageFiles/" . $_FILES["fileImage"]["name"]))


My question is that if a file does exist in the folder, how can it be coded so that it still uploads the file but it gives it a different file name. Maybe something like automatically add a number at the end of the filename to give it a different file name?

share|improve this question
I would argue that uploaded files should generally be stored with names completely distinct from their original names. This way you prevent information disclosure (people changing links from "myfile.txt" to "test.txt", "secret.doc", etc. to see other people's files), don't have to worry about international characters in filenames, and avoid complications in case you need to copy the files to a different filesystem (e.g. copying to Windows for development will mess up if you have "test.txt" and "Test.txt" in the same folder). –  DCoder Apr 14 '12 at 13:59
add comment

2 Answers

up vote 6 down vote accepted

$_FILES is just a variable, that happens to be superglobal and pre-populated with file upload data. Meaning you can easily change it.

For example:

if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
    $parts = explode(".",$_FILES['fileImage']['name']);
    $ext = array_pop($parts);
    $base = implode(".",$parts);
    $n = 2;
    while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
    $_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
// now use $_FILES['fileImage']['name'] just like you would normally
share|improve this answer
add comment

If you want to rename the uploaded file to a name of your own choice, you can try


    //Any file name user/uploader has chosen/used on his/her computer
    $tmp_name = $_FILES["domainfile"]["tmp_name"];

    //Name you want
    $name = "MyDesiredName.png"; //save as MyDesiredName.png

    //Move/save file
    move_uploaded_file($tmp_name, $name);


Obviously this code will replace the old file everytime a new file gets uploaded.
To not to let this happen, you need to introduce some variable in the $name
and do $name++ and to find a way to store its value for future reference.

share|improve this answer
add comment

Your Answer


