TL;DR:
- 使用和下面给出的。random_int()random_str()
- 如果没有 ,请使用 random_compat。random_int()
解释:
由于您正在生成密码,因此您需要确保生成的密码是不可预测的,并且确保此属性存在于实现中的唯一方法是使用加密安全的伪随机数生成器 (CSPRNG)。
对于随机字符串的一般情况,可以放宽对 CSPRNG 的要求,但在涉及安全性时则不放宽。
PHP中密码生成的简单,安全和正确的答案是使用RandomLib,不要重新发明轮子。此库已由行业安全专家以及我自己进行了审核。
对于喜欢发明自己的解决方案的开发人员,PHP 7.0.0 将为此提供 random_int()。如果你还在使用 PHP 5.x,我们为 random_int() 编写了 PHP 5 polyfill,这样你就可以在 PHP 7 发布之前使用新的 API。使用我们的 polyfill 可能比编写自己的实现更安全。random_int()
有了安全的随机整数生成器,生成安全的随机字符串比 pie 更容易:
<?php
/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    $length,
    $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
) {
    $str = '';
    $max = mb_strlen($keyspace, '8bit') - 1;
    if ($max < 1) {
        throw new Exception('$keyspace must be at least two characters long');
    }
    for ($i = 0; $i < $length; ++$i) {
        $str .= $keyspace[random_int(0, $max)];
    }
    return $str;
}