我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
我总是喜欢使用base64来生成随机密码或其他随机(可打印的)字符串。base64的使用确保了大量的可打印字符可用。
在shell上,我通常这样做:
base64 < /dev/urandom |head -c10
在PHP中也可以做类似的事情。然而,直接从/dev/urandom读取可能会被open_basedir限制所禁止。这就是我得出的结论:
base64_encode(
join(
'',
array_map(
function($x){ return chr(mt_rand(1,255));},
range(1,15)
)
)
);
为了得到一个真正随机的字符串,我们也需要随机输入。这就是join/array_map所做的。使用uniqid之类的东西是不够的,因为它总是有一个类似的前缀,因为它基本上是一个美化的时间戳。
如果安装了openssl扩展,当然可以使用openssl_random_pseudo_bytes(),这样会更好。
这段代码将帮助:
此函数将返回长度在$maxLength和$minLength之间的随机字符串。
注意:函数random_bytes从PHP 7开始工作。
如果你需要特定的长度,那么$maxLength和$minLength必须相同。
function getRandomString($maxLength = 20, $minLength = 10)
{
$minLength = $maxLength < $minLength ? $maxLength : $minLength;
$halfMin = ceil($minLength / 2);
$halfMax = ceil($maxLength / 2);
$bytes = random_bytes(rand($halfMin, $halfMax));
$randomString = bin2hex($bytes);
$randomString = strlen($randomString) > $maxLength ? substr($randomString, 0, -1) : $randomString;
return $randomString;
}
只使用PHP本地函数的参数化一行程序,从PHP 5.1.0开始工作
str_shuffle(implode('', (array_intersect_key(($map = array_map('chr', array_merge(array_map('mt_rand', array_fill(0, $length = 25, 48), array_fill(0,$length,57)),array_map('mt_rand', array_fill(0, $length, 65), array_fill(0,$length,90)),array_map('mt_rand', array_fill(0, $length, 97), array_fill(0,$length,122))))), array_flip($keys = array_rand($map, $length))))))
下面是一个简单的单行程序,它生成一个真正的随机字符串,而不需要任何脚本级循环或使用OpenSSL库。
echo substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', mt_rand(1,10))), 1, 10);
把它分解,这样参数就清楚了
// Character List to Pick from
$chrList = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Minimum/Maximum times to repeat character List to seed from
$chrRepeatMin = 1; // Minimum times to repeat the seed string
$chrRepeatMax = 10; // Maximum times to repeat the seed string
// Length of Random String returned
$chrRandomLength = 10;
// The ONE LINE random command with the above variables.
echo substr(str_shuffle(str_repeat($chrList, mt_rand($chrRepeatMin,$chrRepeatMax))), 1, $chrRandomLength);
此方法的工作原理是随机重复字符列表,然后打乱组合的字符串,并返回指定的字符数。
您可以进一步随机化它,通过随机化返回字符串的长度,将$chrRandomLength替换为mt_rand(8,15)(用于8到15个字符之间的随机字符串)。