PHP: generate unique and random numbers/ IDs

南楼画角 提交于 2020-01-25 08:28:10

问题


I want to generate unique and random numbers or IDs which I can use them for email verification, account reset, member invitation purposes, etc

for instance,

http://mywebsite.com/member/9a5af103cd540aa 
http://mywebsite.com/invite/regitration/eef0dd2e0199640 
http://mywebsite.com/reset/account/eef0dd2e0199640 

Here I the code I plan to use, do you think it is safe and 'bullet proof'?

$rand = substr(hash('sha512',uniqid(rand(), true)), 0, 15);
echo $rand;

Or any better options?

Thanks.

EDIT:

I have looked into a couple of options after getting the suggestions from here:

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

I found these two functions from php.net.

But my main concern is - are the numbers/ IDs generated by these two functions unique?

mt_rand - this generate randomness but not uniqueness as far as I understand - am I right?


回答1:


You can use openssl_random_pseudo_bytes () function to generate as many random bytes as you like.




回答2:


You can generate a GUID which for all intents and purposes is unique.




回答3:


I think for the purposes you list, it's by far unique enough. But I'd still check for duplicates, just to be sure. The chances are pretty small, but nonetheless, still there.



来源:https://stackoverflow.com/questions/4776553/php-generate-unique-and-random-numbers-ids

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!