我正在编写一个 PHP 脚本来处理文件上传到服务器。为防止存在同名文件时覆盖,程序会将每个上传的文件重命名为当前时间戳。
然而,这还不够。在高峰时段,可能会有文件在同一秒上传。为了确保上传的文件具有不同的文件名,我正在考虑在时间戳末尾添加一个随机数。
然后,我从 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.
我猜他们正在使用 srand()
的时间戳。如果同一秒上传2个文件,那么srand()
的时间戳,随机结果会一样吗?如果是,有没有一种方法可以确保名称不重复,即使它们是在同一秒上传的?
最佳答案
这是生成种子的代码
#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())))
所以它是时间戳和进程 ID 以及伪随机数的组合
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.
所以,我想说您可以放心,它们不会匹配。
关于php - 如果同时运行mt_rand(),结果会一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40460025/