cytsunny
cytsunny

Reputation: 5030

If mt_rand() is run at the same moment, will the result be the same?

I am writing a PHP script to handle file upload to server. To prevent overwriting when there are files with the same name, the program will rename each uploaded file to the current timestamp.

However, this is not enough. In peak hour, there may be files that are uploaded at the same second. To make sure the uploaded files will have different file names, I am thinking of adding a random number at the end of the timestamp.

Then, I read from the official PHP page on srand()

Note: There is no need to seed the random number generator with srand() or mt_srand() as this is done automatically.

I guess they are using the timestamp for srand(). If 2 files are uploaded at the same second, so the timestamp for srand(), will the random result be the same? If yes, is there a way I can make sure the name is not duplicated even if they are uploaded at the same second?

Upvotes: 3

Views: 270

Answers (3)

Vilx-
Vilx-

Reputation: 106920

PHP has some better random functions too, like random_bytes() and openssl_random_pseudo_bytes(). These will return a guaranteed unique value. Pass it to bin2hex() and you're all set!

Upvotes: 2

Justinas
Justinas

Reputation: 43479

No, seed will be used for random numbers range, not for single number. Than you will be presented single number of that random-generated range. There is still possibility, that you will get same pseudo-random number.

Try adding something like md5(time().$filename.'.'.$extension) instead.

Upvotes: 1

Tschallacka
Tschallacka

Reputation: 28722

This is the code that generates the seeds

#define GENERATE_SEED() (((zend_long) (time(0) * GetCurrentProcessId())) ^ ((zend_long) (1000000.0 * php_combined_lcg())))
#else
#define GENERATE_SEED() (((zend_long) (time(0) * getpid())) ^ ((zend_long) (1000000.0 * php_combined_lcg())))

https://github.com/php/php-src/blob/6053987bc27e8dede37f437193a5cad448f99bce/ext/standard/php_rand.h#L69

So it's a combination of timestamp and process id AND a psuedorandom

https://github.com/php/php-src/blob/6053987bc27e8dede37f437193a5cad448f99bce/ext/standard/lcg.c#L45

combinedLCG() returns a pseudo random number in the range of (0, 1).
The function combines two CGs with periods of
2^31 - 85 and 2^31 - 249. The period of this function
is equal to the product of both primes.

So, i'd say you can rest assured they will not match.

Upvotes: 2

Related Questions