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.
<?php $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.
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.