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

2021-12-21 00:00:00 random php

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

I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.

推荐答案

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

这可能是我最好的猜测——除非您也在寻找特殊字符:

Would be my best guess--Unless you're looking for special characters, too:

$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];

示例

而且,对于基于时钟的一个(因为它是增量的,所以冲突更少):

And, for one based on the clock (fewer collisions since it's incremental):

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")

相关文章