问题
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 )
);
}
回答1:
$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.
来源:https://stackoverflow.com/questions/65648350/will-time-ever-return-the-same-output