我想生成唯一且随机的数字或ID,我可以将它们用于电子邮件验证,帐户重置,会员邀请等目的
例如,
http://mywebsite.com/member/9a5af103cd540aa
http://mywebsite.com/invite/regitration/eef0dd2e0199640
http://mywebsite.com/reset/account/eef0dd2e0199640
在这里,我打算使用的代码,您认为它是安全的吗?'防弹'?
$rand = substr(hash('sha512',uniqid(rand(), true)), 0, 15);
echo $rand;
还是更好的选择?
感谢。
修改
从这里得到建议后,我已经考虑了几个选项:
com_create_guid
function create_guid()
{
if (function_exists('com_create_guid') === true)
{
return trim(com_create_guid(), '{}');
}
# fallback to mt_rand if php < 5 or no com_create_guid available
return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
//return substr(hash('sha512',uniqid(rand(), true)), 0, 15);
}
openssl_random_pseudo_bytes
function generate_password($length = 24) {
if(function_exists('openssl_random_pseudo_bytes')) {
$password = base64_encode(openssl_random_pseudo_bytes($length, $strong));
if($strong == TRUE)
return substr($password, 0, $length); //base64 is about 33% longer, so we need to truncate the result
}
# fallback to mt_rand if php < 5.3 or no openssl available
$characters = '0123456789';
$characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+';
$charactersLength = strlen($characters)-1;
$password = '';
# select some random characters
for ($i = 0; $i < $length; $i++) {
$password .= $characters[mt_rand(0, $charactersLength)];
}
return $password;
}
我从php.net找到了这两个函数。
但我主要担心的是 - 这两个函数生成的数字/ ID是唯一的吗?
mt_rand
- 根据我的理解,这会产生随机性但不是唯一性 - 我是对的吗?