truly unique random number generate by php?

2019-04-17 03:28发布

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.

10条回答
甜甜的少女心
2楼-- · 2019-04-17 03:53

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-17 04:00
$better_token = uniqid(md5(mt_rand()), true);
查看更多
Lonely孤独者°
4楼-- · 2019-04-17 04:03

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.

 $candidate_name=generate_hash_of_file($input_file);
 $offset=0;
 while ((file_exists($candidate_name . strrev($offset) && ($offset<50)) {
    $offset++;
 }
 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.

C.

查看更多
Melony?
5楼-- · 2019-04-17 04:03

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.

查看更多
登录 后发表回答