Smart Way for Renaming Uploaded Files Using PHP

Today I would like to share with you this nice technique of renaming an uploaded file. It is a good practice to rename files after upload to make sure you get rid of weird characters and spaces. There are many ideas out there but I personally like this one. Ok, enough with the talk and let’s get down to business.

  $randString = md5(time()); //encode the timestamp - returns a 32 chars long string
  $fileName = $_FILES["uploaded_file"]["name"]; //the original file name
  $splitName = explode(".", $fileName); //split the file name by the dot
  $fileExt = end($splitName); //get the file extension
  $newFileName  = strtolower($randString.'.'.$fileExt); //join file name and ext.

So in the code above first we get the current time stamp and then encode it using the md5() function which gives us a string of 32 characters. This way we are sure to always get a different name because obviously the time stamp is continuously changing.

After that we get the uploaded file name and split it into two parts using the dot and that is just to get the extension of the uploaded file.

Finally we rejoin the new 32 characters long unique file name with the extension of the uploaded file and here we have a new file name.

This code does not check for the uploaded file type so make sure you use a file type validation script before uploading files to your server.

For more stable and advanced random string generation methods please visit Generate Random Strings Using PHP.

I hope that this simple tutorial was helpful for you.

Smart Way for Renaming Uploaded Files Using PHP
4 votes, 4.50 avg. rating (87% score)
  • Posted in: PHP
Husamaldin Tayeh

Posted by

Husamaldin is a computer programmer, blogger, entrepreneur and an overall thinker. He is the founder and editor of Coders Mount. He loves everything about computers and programming. Find out more about him here or follow him on Twitter Google+ | LinkedIn.

  • Doaa

    Great tutorial, thanks a lot.

    • Husamaldin

      You are welcome

  • David

    Very simple tutorial, extremely useful . . . please add more stuff like this !

  • DampeS8N

    This code has three potentially serious problems.

    1) time() returns seconds, so if two files are uploaded at the same time, they will overwrite each other.
    2) md5() has a collision rate, and eventually you will overwrite an older file with a newer one when those values collide.
    3) This code contains no security checks.
    A) The file type is not checked, so users could easily upload .exe or .php files to your server. This would let them distribute malware, or use you as a proxy to attack other servers.
    B) The file may have a different mime type than its file extension, resulting in A even if you have a white list of file extensions.

    A better way to solve 1 and 2 is to use the key you’ve stored the file references in your database under. This has the added benefit to be user friendly. 3 can be solved by inspecting the files more deeply and by keeping a strict white list of allowed file types.

    • Husamaldin

      Thanks for the info. As for issues 1 and 2 you could be right but the chances of this happening are really slim. Maybe on a really busy website with thousands of users then yes this could cause a problem and files get overwritten. As for the 3rd issue of course there should be a file validation script but this was not the topic of this tutorial. As you may have noticed this tutorial is for beginners. Your comment is really appreciated.

    • DampeS8N

      It is exactly because this is for beginners that the warning (which I don’t believe was present when I left my comment) is needed. I’m glad that it is there. We must be mindful of the security of the code we post as complete. Issues 1 and 2 may never be a problem for 99% of users, for example, but you’ll really ruin the day of that 1%. And the fixes are easy.

      If you don’t want to use your database key, you could also add microtime() and/or the initial file name to the hash and the file size to the end of the file name. Hash + filesize are now in the once-in-a-universe range of probabilities for collision.

      As programmers we need to be mindful of slim chances, they are often the ones that come back and bite us. Acknowledging those issues is exactly what we should do to teach beginners. They, probably more than we, need the extra help with understanding these issues of security. Because, they are the least equipped to deal with a breach should one occur.

      If someone were to follow this tutorial and suffer a serious hack, which they could very easily if they don’t limit what files can be uploaded correctly. They wouldn’t just get egg on their face. If they aren’t properly equipped to track down the malicious files, they could find themselves in jail. All it would take is their server being used, by proxy, to break into the wrong people’s network. Things like this have happened. And they are most commonly caused by irresponsible tutorial code.

      FYI – I’ve now used your captcha twice, and I don’t think it would be difficult to reverse engineer the relationship between your hash and the characters it represents. A simple rainbow table would make it moot. Additionally, the image changes each time you load it, so it would be easy to run a text recognition system over 100 or so examples of the image, and then pick the letters with the highest probability.

  • Aaron

    I’ve implemented your code and it works great, except that it’s leaving off the extension from the file in my upload folder. Is there something I’m missing?

    • Husamaldin Tayeh

      Hi Aaron,
      Make sure that the name attribute of the file input is the same as the one in $_FILES array $fileName = $_FILES[“uploaded_file”][“name”];

      i.e if you name the file input “myfile” then make sure that your php code becomes as follows: $fileName = $_FILES[“myfile”][“name”];

      Your problem is very likely a result of name mismatch between the input field and the php $_FILES array, so the $_FILES array is not getting the file name and hence cannot produce an extension for it.

      Please let me know if this helps.

  • hamara

    hi, hw i join this code with orginal code of mine…tizz is mine plzz correct it

    $FOLDER = $_POST[‘select’];

    // Where the file is going to be placed

    $target_path = “C:UsersuserDesktop/”.$FOLDER.”/”;

    /* Add the original filename to our target path. Result is “uploads/filename.extension” */

    $upload2 = $target_path .”/”. basename ( $_FILES[‘uploadedfile’][‘name’] ) ;

    // This is how we will get the temporary file…


    $target_path = “C:UsersuserDesktop/”.$FOLDER.”/”;

    $upload2 = $target_path .basename ( $_FILES[‘uploadedfile’][‘name’]) ;

    if(move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $upload2 ))

  • Jeevan Patnaik

    I dont get it! here, new file name value is assigned to only the newfilename variable..but how come the name of the actual file changes..please explain! am I wrong anywhere?

    • Husamaldin Tayeh

      I didn’t quite get your question. What this code does is that it grabs the name of the uploaded file and splits it by the dot inorder to get the extension of the file and then generates a random string of 32 characters before joining it again with the file extension.

  • وحید الوندی

    tank you

  • Hardik Raval

    hello your concept is very nice, but what will happen when two files will be uploaded at same time stamp by two different clients/users? this case may happen when the app is too large system like facebook or google+