php - 如果同时运行mt_rand(),结果会一样吗?

标签 php random

我正在编写一个 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())))

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

所以它是时间戳和进程 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/

相关文章:

php - CakePHP - 从同一模型中的另一个函数调用模型函数

php - $_SERVER ['DOCUMENT_ROOT'] 不工作

javascript - Ajax 404(未找到)循环遍历

algorithm - 如何生成相关的二元变量

python - 随机生成图像

c - `clear` 导致 undefined reference 错误

php - PHP Mongo 聚合中的多个 $match

java - 如何在 Android Studio 自己的方法中检索从 For 循环所做的值更改?

html - JavaScript : Random Style Class Using Math. 随机()

php - 计算 GROUP_CONCAT 内的值