【问题标题】:PHP: generate unique and random numbers/ IDsPHP:生成唯一和随机数/ ID
【发布时间】:2011-06-14 04:13:48
【问题描述】:

我想生成唯一且随机的数字或 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 - 据我所知,这会产生随机性,但不会产生唯一性 - 对吗?

【问题讨论】:

  • 我会使用 bin2hex 而不是 base64_encode

标签: php random


【解决方案1】:

您可以使用openssl_random_pseudo_bytes () 函数生成任意数量的随机字节。

【讨论】:

  • 好吧,如果你用这个函数生成 32 个字节,我会说它们足够独特。
【解决方案2】:

您可以生成一个GUID,无论出于何种目的和目的,它都是unique.

【讨论】:

  • 它属于 Windows Only Extensions 类别。
【解决方案3】:

我认为就您列出的目的而言,它已经足够独特了。但为了确定,我仍然会检查重复项。机会很小,但仍然存在。

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多