Search code examples
phpfilenames

Will PHP Use a Used tmp_name Again?


I’m having a file upload system in my website for a long time. During the time, I realized that many users upload files that contain same names but are different from each other. As the names are same, the upload fails! I’ve decided not to use the $_FILES['file']['name'] for the filenames again.

In my case, a random echo of a $_FILES['file']['tmp_name'] looks like /tmp/phpynIF3G. I’m going to use the $_FILES['file']['tmp_name'] for the file name.

For example, at first it was $filename = $_FILES['file']['name']; and now it’d be $filename = str_replace("/tmp/php","",$_FILES['file']['tmp_name']).".jpg";. So, when the file will be successfully uploaded to my /e/ directory, it can be accessed by a url which is https://sitename/e/ynIF3G.jpg.

If Php has already used the /tmp/phpynIF3G once, will it ever use the same tmp_name for an other file again?


Solution

  • If each user uploads a file named XYZ.jpg, and if you want them to not be overwriten, you have to either validate if the file exists and change its name or separate where to save the files.

    Usually, theres a file directory that can you structure your files, something like user/userid/files/XYZ.jpg.

    $_FILES['file']['tmp_name'] is a name, temporary for that matter, randomly generated. It is possible, altho unlikely, that it may repeat itself eventually.

    May I suggest, if you don't want to take the approach of having folders to separate the files, you use:

    while (file_exists($_FILES['file']['name'])) {
    //If exists, then just add a random string to the end of the file
    //This is just an example of an approach, what this will do is make your file look like: filename.jpg.aksjwq, 
    //The rest is homework for you, to work an improved solution, I'm just here to give you the idea :P
        $_FILES['file']['name'] .= randomString(6);
    }
    
    function randomString($length = 6) {
        $str = "";
        $characters = array_merge(range('A','Z'), range('a','z'), range('0','9'));
        $max = count($characters) - 1;
        for ($i = 0; $i < $length; $i++) {
            $rand = mt_rand(0, $max);
            $str .= $characters[$rand];
        }
        return $str;
    }