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

2022-08-30 07:30:35

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


答案 1
$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”)


答案 2

如果循环供不应求,我喜欢使用以下内容:for

$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);

推荐