time() 会返回相同的输出吗? [英] Will time() ever return the same output?

查看:73
本文介绍了time() 会返回相同的输出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用户注册时使用 PHP 为他们生成令牌.我想知道两个用户是否可以获得相同的令牌......因为这会破坏系统.请让我知道这是否足够.

I am generating tokens for users in PHP when they register. I am wondering if two users could ever get the same token... as this will break the system. Please let me know if this is suffiecient.

$token = md5(rand().time());

我现在正在使用我在另一个问题上找到的 generate_uuid() 函数.这行得通吗?

edit: i am now using a generate_uuid() function i found on another question. will this work?

function generate_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
        mt_rand( 0, 0xffff ),
        mt_rand( 0, 0x0C2f ) | 0x4000,
        mt_rand( 0, 0x3fff ) | 0x8000,
        mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
    );

}

推荐答案

$token = md5(rand().time());

很有可能不再重复.

  • Time() 会在一秒内重复.
  • 如果是夏令时,Time() 每年重复一个小时.
  • 但是 rand() 不会重复 2^30 步.
  • MD5 不会增加随机性,甚至可能会降低随机性.

mt_rand() 非常擅长随机性",但这意味着它可以并且会重复——在随机"次.不要不要相信它不会重复.

mt_rand() is very good at "randomness", but that means that it can and will repeat -- at "random" times. Do not trust it for not repeating.

另见microtime(true);它精确到微秒.但它仍然会导致重复,尤其是当两个不同的客户使用相同的公式时.

See also microtime(true); it is precise to the microsecond. But it still can lead to dups, especially if two different clients are using the same formula.

只需使用 UUID 函数即可.他们有很多研究和思想投入其中.你不必要地重新发明轮子.请参阅这个了解为什么 UUID 会影响性能 在数据库中以及如何处理它.

Simply use UUID functions. They have a lot of research and thought put into them. You are unnecessarily re-inventing the wheel. See this for why UUIDs mess with performance in a database and what to do about it.

这篇关于time() 会返回相同的输出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆