1

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?

1
  • 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). Commented Apr 14, 2012 at 13:59

2 Answers 2

5

$_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
Sign up to request clarification or add additional context in comments.

Comments

0

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

<?php

    //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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.