php获取随机字符串

php获取随机字符串

PHP获取随机字符串实现代码如下:

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

输出随机字符串,调用方式如下:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

生成token

这个问题有很多答案,但是没有一个可以利用加密安全的伪随机数生成器。

对于那些坚持自己发明解决方案的人,PHP 7.0.0将提供random_int();如果你还在用PHP 5。我们为random_int()写了一个PHP 5的polyfill,这样在升级到PHP 7之前就可以使用新的API了。

在PHP中安全地生成随机整数并不是一项简单的任务。在将自行开发的算法部署到生产环境之前,您应该始终与您的常驻StackExchange密码专家进行检查。

有了安全的整数生成器后,使用CSPRNG生成随机字符串就变的简单。

/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 *
 * This function uses type hints now (PHP 7+ only), but it was originally
 * written for PHP 5 as well.
 * 
 * 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(
    int $length = 64,
    string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
    if ($length < 1) {
        throw new \RangeException("Length must be a positive integer");
    }
    $pieces = [];
    $max = mb_strlen($keyspace, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pieces []= $keyspace[random_int(0, $max)];
    }
    return implode('', $pieces);
}

使用

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();
(0)
上一篇 2020年10月19日 下午3:07
下一篇 2020年10月19日 下午3:43

相关推荐

发表回复

登录后才能评论