dov11020 2016-11-07 07:38
浏览 292

如果同时运行mt_rand(),结果是否相同?

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?

  • 写回答

3条回答 默认 最新

  • dongyan6235 2016-11-07 07:45
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么