PHP:生成唯一和随机的数字/ID [英] PHP: generate unique and random numbers/ IDs

查看:101
本文介绍了PHP:生成唯一和随机的数字/ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成唯一的随机数字或 ID,我可以将它们用于电子邮件验证、帐户重置、会员邀请等目的

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

例如

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;

或者有更好的选择吗?

谢谢.

从这里得到建议后,我研究了几个选项:

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

我从 php.net 上找到了这两个函数.

I found these two functions from php.net.

但我主要关心的是 - 这两个函数生成的数字/ID 是唯一的吗?

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

mt_rand - 据我所知,这会产生随机性,但不会产生唯一性 - 对吗?

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

推荐答案

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

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

这篇关于PHP:生成唯一和随机的数字/ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆