生成随机的5个字符的字符串

我想创建精确的5个随机字符串,并尽可能减少重复。最好的方法是什么?谢谢。

回答:

$rand = substr(md5(microtime()),rand(0,26),5);

这将是我最好的猜测-除非您也要寻找特殊字符:

$seed = str_split('abcdefghijklmnopqrstuvwxyz'

.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

.'0123456789!@#$%^&*()'); // and any other characters

shuffle($seed); // probably optional since array_is randomized; this may be redundant

$rand = '';

foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];

而且,对于基于时钟的时钟(由于它是递增的,因此冲突较少):

function incrementalHash($len = 5){

$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

$base = strlen($charset);

$result = '';

$now = explode(' ', microtime())[1];

while ($now >= $base){

$i = $now % $base;

$result = $charset[$i] . $result;

$now /= $base;

}

return substr($result, -5);

}

注意:增量意味着更容易猜测; 如果您将其用作盐或验证令牌,请不要使用。盐(现在)为“ WCWyb”表示从现在起5秒钟为“ WCWyg”)

以上是 生成随机的5个字符的字符串 的全部内容, 来源链接: utcz.com/qa/428669.html

回到顶部