Home » Php » php random image file name

php random image file name

Posted by: admin July 12, 2020 Leave a comment


Okay im using a snippet I found on google to take a users uploaded image and put it in my directory under Content

But Im worried about duplicates so I was going have it upload the image as a Random number

well here is my code you can probably understand what im going for through it anyways

<label for="file">Profile Pic:</label> <input type="file" name="ProfilePic" id="ProfilePic" /><br />

<input type="submit" name="submit" value="Submit" />

$ProfilePicName = $_FILES["ProfilePic"]["name"];
$ProfilePicType = $_FILES["ProfilePic"]["type"];
$ProfilePicSize = $_FILES["ProfilePic"]["size"];
$ProfilePicTemp = $_FILES["ProfilePic"]["tmp_name"];
$ProfilePicError = $_FILES["ProfilePic"]["error"];

$RandomAccountNumber = mt_rand(1, 99999);  
echo $RandomAccountNumber; 
move_uploaded_file($ProfilePicTemp, "Content/".$RandomAccountNumber.$ProfilePicType);

And then basicly after all this Im going try to get it to put that random number in my database

Someone gave me a new snippet that looks like it will do what I want but now the file isnt making it all the way to my directory

$RandomAccountNumber = uniqid();
echo $RandomAccountNumber;

How to&Answers:

try using the php uniqid method to generate the unique id you need


$RandomAccountNumber = uniqid();
move_uploaded_file($ProfilePicTemp, "Content/" . $RandomAccountNumber);


When I upload images, I usually save it as the sha1() of the image’s contents (sha1_file()). That way, you get two birds with one stone: You’ll never (if you do, go fill out the closest lottery) get duplicate file names, AND, you’ll prevent duplicate images (because duplicate images would have the same checksum).

Then, you have a database to sort out which image is which, and correctly display them to the user.


This is what I use when uploading pictures: a combination of session_id(), time() and a random string:

$rand = genRandomString();
$final_filename = $rand."_".session_id()."_".time();

function genRandomString() 
    $length = 5;
    $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ";

    $real_string_length = strlen($characters) ;     

    for ($p = 0; $p < $length; $p++) 
        $string .= $characters[mt_rand(0, $real_string_length-1)];

    return strtolower($string);

I hope this help.


random != unique

No matter what method you use to generate a ‘random’ file name you’re probably going to want to do this to avoid collisions.

$path = '/path/to/directory/';
do {
    $filename = some_function();
} while( file_exists($path.$filename) );

It’s not super-necessary, but if you’re just looking for peace of mind in case of a one-in-a-million filename collision then those couple extra lines will do the trick.


One of my favorite Coding Horror articles addresses why this approach is dumber than it looks, and you should use something like uniqid instead of mt_rand(1, 99999);