PHP7中的随机字符串

nin*_*sky 2 php random

我正在尝试使用PHP7的闪亮的新random_bytes()函数来创建一个8和12随机字符串.

官方PHP文档中,只有一个示例如何使用bin2hex()创建十六进制字符串.为了获得更大的随机性,我想生成一个字母数字[a-zA-Z0-9]字符串,但找不到如何实现这一点的方法.

在此先感谢您的帮助
ninsky

axi*_*iac 5

使用随机字节的ASCII代码作为字符数组(或字符串)的索引.像这样的东西:

// The characters we want in the output
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$count = strlen($chars);

// Generate 12 random bytes
$bytes = random_bytes(12);

// Construct the output string
$result = '';
// Split the string of random bytes into individual characters
foreach (str_split($bytes) as $byte) {
    // ord($byte) converts the character into an integer between 0 and 255
    // ord($byte) % $count wrap it around $chars
    $result .= $chars[ord($byte) % $count];
}

// That's all, folks!
echo($result."\n");
Run Code Online (Sandbox Code Playgroud)