PHP: generate unique and random numbers/ IDs

2019-08-17 04:11发布

问题:

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.



标签: php random