简体   繁体   English

生成10位随机确认字符串php

[英]Generating a 10 digit random confirmation string php

I am trying to create a 'confirmation code' for every user account created on my website and storing it in the db along with their personal information. 我正在尝试为我网站上创建的每个用户帐户创建一个“确认代码”,并将其与个人信息一起存储在数据库中。 As you can see in the example below, I tried to generate a random string factoring in the time variable, however, the string is unneccessarily long. 正如您在下面的示例中所看到的,我尝试在时间变量中生成随机字符串因子,但是,字符串是不必要的长。

I would like the string to be shorter than the one produced by md5 I was wondering if there is a relatively easy way to generate 10 digit (max) alphanumeric string that has an extremely low collision rate? 我希望字符串比md5生成的字符串更短我想知道是否有一种相对简单的方法来生成具有极低冲突率的10位(最大)字母数字字符串?

What I tried: 我尝试了什么:

  md5(mt_rand(10000,99999).time() . 'example@domain.com');

Output: 输出:

0dd6854dba19e70cfda0ab91595e0376

PHP provides the openssl_random_pseudo_bytes function that can be made to securely do what you want. PHP提供openssl_random_pseudo_bytes函数,可以安全地执行您想要的操作。

Do something like: 做类似的事情:

bin2hex(openssl_random_pseudo_bytes(5))

The above will give you something like e9d196aa14 , for example. 例如,上面的内容将为您提供类似e9d196aa14

Alternatively, just take the first 10 chars of your existing MD5 string. 或者,只需获取现有MD5字符串的前10个字符。

This will generate you any random output string from Aa-Zz and 0-9 characters. 这将生成来自Aa-Zz0-9字符的任何随机输出字符串。

function genString($length) {
    $lowercase = "qwertyuiopasdfghjklzxcvbnm";
    $uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP";
    $numbers = "1234567890";
    $specialcharacters = "{}[];:,./<>?_+~!@#";
    $randomCode = "";
    mt_srand(crc32(microtime()));
    $max = strlen($lowercase) - 1;
    for ($x = 0; $x < abs($length/3); $x++) {
        $randomCode .= $lowercase{mt_rand(0, $max)};
    }
    $max = strlen($uppercase) - 1;
    for ($x = 0; $x < abs($length/3); $x++) {
        $randomCode .= $uppercase{mt_rand(0, $max)};
    }
    $max = strlen($specialcharacters) - 1;
    for ($x = 0; $x < abs($length/3); $x++) {
        $randomCode .= $specialcharacters{mt_rand(0, $max)};
    }
    $max = strlen($numbers) - 1;
    for ($x = 0; $x < abs($length/3); $x++) {
        $randomCode .= $numbers{mt_rand(0, $max)};
    }
    return str_shuffle($randomCode);
}

Usage 用法

$str = genString(10);

I think the best way is 我认为最好的方法是

$random = substr(number_format(time() * rand(),0,'',''),0,10); // you can increase the digits by changing 10 to desired digit

Please check it out 请检查一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM