我想生成獨特隨機數或ID,我可以使用他們的電子郵件驗證,賬戶復位,會員邀請目的等PHP:生成獨特隨機數/ IDS
例如,
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 = '';
$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
- 據我瞭解,這會產生隨機性但不是唯一性 - 我是對嗎?
而不是base64_encode我會使用bin2hex – catalint 2014-03-06 11:56:26