如何可能生成一个随机的,唯一的字符串使用数字和字母用于验证链接?就像你在一个网站上创建了一个账户,它会给你发一封带有链接的电子邮件,你必须点击那个链接才能验证你的账户

如何使用PHP生成其中一个?


当前回答

这个函数将使用数字和字母生成一个随机键:

function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}

echo random_string(50);

示例输出:

zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8

其他回答

一个简单的解决方案是通过丢弃非字母数字字符将64进制转换为字母数字。

它使用random_bytes()来获得加密安全的结果。

function random_alphanumeric(int $length): string
{
    $result='';
    do
    {
        //Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
        $bytes=random_bytes(($length+3-strlen($result))*2);
        //Discard non-alhpanumeric characters
        $result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
        //Keep adding characters until the string is long enough
        //Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
    }while(strlen($result)<$length+3);
    return substr($result,0,$length);
}

编辑:我只是重新审视了一下,因为我需要一些更灵活的东西。这里有一个解决方案,执行得比上面的好一点,并提供了指定ASCII字符集的任何子集的选项:

<?php
class RandomText
{
    protected
        $allowedChars,
        //Maximum index to use
        $allowedCount,
        //Index values will be taken from a pool of this size
        //It is a power of 2 to keep the distribution of values even
        $distributionSize,
        //This many characters will be generated for each output character
        $ratio;
    /**
     * @param string $allowedChars characters to choose from
     */
    public function __construct(string $allowedChars)
    {
        $this->allowedCount = strlen($allowedChars);
        if($this->allowedCount < 1 || $this->allowedCount > 256) throw new \Exception('At least 1 and no more than 256 allowed character(s) must be specified.');
        $this->allowedChars = $allowedChars;
        //Find the power of 2 equal or greater than the number of allowed characters
        $this->distributionSize = pow(2,ceil(log($this->allowedCount, 2)));
        //Generating random bytes is the expensive part of this algorithm
        //In most cases some will be wasted so it is helpful to produce some extras, but not too many
        //On average, this is how many characters needed to produce 1 character in the allowed set
        //50% of the time, more characters will be needed. My tests have shown this to perform well.
        $this->ratio = $this->distributionSize / $this->allowedCount;
    }

    /**
     * @param int $length string length of required result
     * @return string random text
     */
    public function get(int $length) : string
    {
        if($length < 1) throw new \Exception('$length must be >= 1.');
        $result = '';
        //Keep track of result length to prevent having to compute strlen()
        $l = 0;
        $indices = null;
        $i = null;
        do
        {
            //Bytes will be used to index the character set. Convert to integers.
            $indices = unpack('C*', random_bytes(ceil(($length - $l) * $this->ratio)));
            foreach($indices as $i)
            {
                //Reduce to the smallest range that gives an even distribution
                $i %= $this->distributionSize;
                //If the index is within the range of characters, add one char to the string
                if($i < $this->allowedCount)
                {
                    $l++;
                    $result .= $this->allowedChars[$i];
                }
                if($l >= $length) break;
            }
        }while($l < $length);
        return $result;
    }
}

我总是使用这个my函数来生成一个自定义随机字母数字字符串…希望这对你有所帮助。

<?php
  function random_alphanumeric($length) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
    $my_string = '';
    for ($i = 0; $i < $length; $i++) {
      $pos = random_int(0, strlen($chars) -1);
      $my_string .= substr($chars, $pos, 1);
    }
    return $my_string;
  }
  echo random_alphanumeric(50); // 50 characters
?>

例如,它生成:Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86g

如果你想与另一个字符串进行比较,以确保它是唯一的序列,你可以使用这个技巧…

$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
  $string_1 = random_alphanumeric(50);
  $string_2 = random_alphanumeric(50);
  if ($string_1 != $string_2) {
     break;
  }
}
echo $string_1;
echo "<br>\n";
echo $string_2;

它生成两个唯一的字符串:

qsBDs4JOoVRfFxyLAOGECYIsWvpcpMzAO9pypwxsqPKeAmYLOi

Ti3kE1WfGgTNxQVXtbNNbhhvvapnaUfGMVJecHkUjHbuCb85pF

希望这就是你想要的……

当尝试生成一个随机密码时,您正在尝试:

首先生成一组加密安全的随机字节 第二是将这些随机字节转换为可打印的字符串

现在,在php中有多种生成随机字节的方法,例如:

$length = 32;

//PHP 7+
$bytes= random_bytes($length);

//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);

然后你想把这些随机字节转换成一个可打印的字符串:

你可以使用bin2hex:

$string = bin2hex($bytes);

或者base64_encode:

$string = base64_encode($bytes);

但是,请注意,如果使用base64,则不能控制字符串的长度。 你可以使用bin2hex来做到这一点,使用32字节将变成一个64字符的字符串。 但它只会在EVEN字符串中这样工作。

所以基本上你可以这样做:

$length = 32;

if(PHP_VERSION>=7){
    $bytes= random_bytes($length);
}else{
    $bytes= openssl_random_pseudo_bytes($length);
} 

$string = bin2hex($bytes);

如果您想在PHP中生成一个唯一的字符串,请尝试以下操作。

md5(uniqid().mt_rand());

在这方面,

uniqid() -它将生成唯一的字符串。此函数返回基于时间戳的唯一标识符作为字符串。

mt_rand() -生成随机数。

md5() -它将生成哈希字符串。

我在这里提供了一些很好的研究数据,基于斯科特的答案提供的功能。因此,我为这个为期5天的自动化测试设置了一个数字海洋液滴,并将生成的唯一字符串存储在MySQL数据库中。

在这个测试期间,我使用了5个不同的长度(5、10、15、20、50),每个长度插入+/- 50万条记录。在我的测试中,在50万个重复中,只有长度5产生了+/-3K个重复,其余长度没有产生任何重复。所以我们可以说,如果我们使用Scott函数的长度为15或以上,那么我们就可以生成高度可靠的唯一字符串。以下是我的研究数据:

更新

我使用这些函数创建了一个简单的Heroku应用程序,它将令牌作为JSON响应返回。该应用程序可以在https://uniquestrings.herokuapp.com/api/token?length=15上访问