Reputation: 163
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 )
);
}
Upvotes: 0
Views: 103
Reputation: 142296
$token = md5(rand().time());
Has a good chance of never repeating.
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.
Upvotes: 2