PHP7中的随机字符串


Random string in PHP7

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

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

提前感谢您的帮助
ninsky

使用随机字节的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");

您可以使用另外两种方法。根据[a-zA-Z0-9]制作数组,然后为1。从该阵列2中取6或8个随机元素。打乱这个数组,从开始或从数组的任何部分取出6或8个元素

<?php
$small_letters = range('a', 'z');
$big_letters = range('A', 'Z');
$digits = range (0, 9);
$res = array_merge($small_letters, $big_letters, $digits);
$c = count($res);
// first variant
$random_string_lenght = 8;
$random_string = '';
for ($i = 0; $i < $random_string_lenght; $i++)
{
    $random_string .= $res[random_int(0, $c - 1)];
}
echo 'first variant result ', $random_string, "'n";
// second variand
shuffle($res);
$random_string = implode(array_slice($res, 0, $random_string_lenght));
echo 'second variant result ', $random_string, "'n";