Take the 2-minute tour ×

I'm have build an up php script to host large number of images upload by user, what is the best way to generate random numbers to image filenames so that in future there would be no filename conflict? Be it like Imageshack. Thanks.

share|improve this question
Random != Unique. The two have nothing to do with each other. Random numbers include duplicates -- scattered around randomly in the sequence of numbers. –  S.Lott May 14 '10 at 11:45
Are the images associated with database records? If so, you could just use the primary key as the filename, since that's guaranteed to be unique. –  Will Vousden May 14 '10 at 11:52
Would it be safe not to lookup the database records? I have look up if the file is exist in the folder through PHP. –  proyb2 May 14 '10 at 12:04
Of course you could look it up in the database, but the UUID approach doesn't require the need to, so why bother? –  apg May 14 '10 at 12:14
Maybe he will have to insert a record in the db anyway. –  Lohoris May 14 '10 at 13:56

9 Answers 9

up vote -1 down vote accepted

Keep a persistent list of all the previous numbers you've generated(in a database table or in a file) and check that a newly generated number is not amongst the ones on the list. If you find this to be prohibitively expensive, generate random numbers on a sufficient number of bits to guarantee a very low probability of collision.

You can also use an incremental approach of assigning these numbers, like a concatenation of a timestamp_part based on the current time and a random_part, just to make sure you don't get collisions if multiple users upload files at the same time.

share|improve this answer
This solution does not scale well –  symcbean May 14 '10 at 12:37
$better_token = uniqid(md5(mt_rand()), true);
share|improve this answer

Easiest way would be a new GUID for each file.


share|improve this answer
are these truly unique for a million of images? –  proyb2 May 14 '10 at 12:07
en.wikipedia.org/wiki/…. You have a better chance of being hit by a meteorite. –  apg May 14 '10 at 12:12
still not a reason to avoid a system that is really unique. –  Lohoris May 14 '10 at 14:23
@Lo'oris: not getting hit by a meteorite sounds like a good reason. –  Andrey Fedorov May 14 '10 at 18:19

Here's how I implemented your solution

This example assumes i want to

  • Get a list, containing 50 numbers that is unique and random, and
  • This list of # to come from the number range of 0 to 1000


 //developed by www.fatphuc.com

 $array = array(); //define the array

 //set random # range
 $minNum = 0;
 $maxNum = 1000;

// i just created this function, since we’ll be generating
// # in various sections, and i just want to make sure that
// if we need to change how we generate random #, we don’t 
// have to make multiple changes to the codes everywhere. 
// (basically, to prevent mistakes)

function GenerateRandomNumber($minNum, $maxNum){
   return round(rand($minNum, $maxNum));

//generate 49 more random #s to give a total of 50 random #s
for($i = 1; $i <= 49; $i++){
    $num1 = GenerateRandomNumber($minNum, $maxNum);   
        while(in_array($num1, $array)){
            $num1 = GenerateRandomNumber($minNum, $maxNum);
    $array[$i] = $num1;

asort($array); //just want to sort the array

//this simply prints the list of #s in list style
echo '<ol>';
foreach ($array as $var){
    echo '<li>';
    echo $var;
    echo '</li>';
echo '</ol>';
share|improve this answer

You could use microtime() as suggested above and then appending an hash of the original filename to further avoid collisions in the (rare) case of exact contemporary uploads.

share|improve this answer
I like this best. A hash created from the current timestamp, the current user name, the file name, and an incremental global upload counter would be 100% duplicate safe. –  Pekka 웃 May 14 '10 at 11:53
You can add more to the mix, like info from the client e.g. ip address etc... –  zaf May 14 '10 at 11:59
Why? Why not just use an incremental global counter? That's the only part of all of this that's ensuring 0 collisions. –  Jeriko May 14 '10 at 12:13
or, as I suggested, just create a name without putting too much effort in it and just check it before committing. –  Lohoris May 14 '10 at 13:40

There are several flaws in your postulate that random values will be unique - regardless of how good the random number generator is. Also, the better the random number generator, the longer it takes to calculate results.

Wouldn't it be better to use a hash of the datafile - that way you get the added benefit of detecting duplicate submissions.

If detecting duplicates is known to be a non-issue, then I'd still recommend this approach but modify the output based on detected collisions (but using a MUCH cheaper computation method than that proposed by Lo'oris) e.g.

 while ((file_exists($candidate_name . strrev($offset) && ($offset<50)) {
 if ($offset<50) {
    rename($input_file, $candidate_name . strrev($offset));
 } else {
    print "Congratulations - you've got the biggest storage network in the world by far!";

this would give you the capacity to store approx 25*2^63 files using a sha1 hash.

As to how to generate the hash, reading the entire file into PHP might be slow (particularly if you try to read it all into a single string to hash it). Most Linux/Posix/Unix systems come with tools like 'md5sum' which will generate a hash from a stream very efficiently.


share|improve this answer
  1. forge a filename
  2. try to open that file
  3. if it exists, goto 1
  4. create the file
share|improve this answer

Using something based on a timestamp maybe. See the microtime function for details. Alternatively uniqid to generate a unique ID based on the current time.

share|improve this answer
Basing just on a timestamp will not give you unique results. –  devoured elysium May 14 '10 at 11:47
@devoured, you have a point :-) –  richsage May 14 '10 at 12:15

My solution is usually a hash (MD5/SHA1/...) of the image contents. This has the added advantage that if people upload the same image twice you still only have one image on the hard disk, saving some space (ofc you have to make sure that the image is not deleted if one user deletes it and another user has the same image in use).

share|improve this answer
hashes, by definition, are not unique. (though of course collision is unlikely) –  Lohoris May 14 '10 at 13:37

Your Answer


