Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

php - Will time() ever return the same output?

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());

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 )
    );

}
question from:https://stackoverflow.com/questions/65648964/will-this-function-i-made-return-a-unique-string-every-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$token = md5(rand().time());

Has a good chance of never repeating.

  • Time() does repeat within one second.
  • Time() repeats for an hour once a year if it is on daylight savings.
  • But rand() does not repeat for 2^30 steps.
  • MD5 does not increase the randomness, and may even decrease it.

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...