1

我正在尝试为在我的网站上创建的每个用户帐户创建一个“确认代码”,并将其与他们的个人信息一起存储在数据库中。正如您在下面的示例中所看到的,我尝试生成一个包含时间变量的随机字符串,但是,该字符串不必要地长。

我希望字符串比生成的字符串短,md5我想知道是否有一种相对简单的方法可以生成冲突率极低的 10 位(最大)字母数字字符串?

我尝试了什么:

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

输出:

0dd6854dba19e70cfda0ab91595e0376
4

5 回答 5

4

PHP 提供了openssl_random_pseudo_bytes可以安全地做你想做的事情的功能。

执行以下操作:

bin2hex(openssl_random_pseudo_bytes(5))

例如,上面会给你一些类似的东西e9d196aa14

或者,只取现有 MD5 字符串的前 10 个字符。

于 2012-07-02T20:14:29.397 回答
1

http://php.net/manual/en/function.uniqid.php

+

http://br.php.net/manual/en/function.substr.php

于 2012-07-02T20:07:44.907 回答
0

这将为您生成任何随机输出字符串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);
}

用法

$str = genString(10);
于 2012-09-22T02:42:14.007 回答
0

我认为最好的方法是

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

请检查一下

于 2014-07-22T13:59:27.990 回答
-1

尝试使用http://php.net/manual/en/function.str-split.php

于 2012-07-02T20:09:52.883 回答