我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
$t = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
echo join('', array_map(function() use($t) { return $t[array_rand($t)]; }, range(1, 15)));
或一行程序
echo join('', array_map(function() { return substr('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', rand(0, 61), 1); }, range(1, 15)));
首先,定义你想要使用的字母:
$alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$special = '~!@#$%^&*(){}[],./?';
$alphabet = $alphanum . $special;
然后,使用openssl_random_pseudo_bytes()生成适当的随机数据:
$len = 12; // length of password
$random = openssl_random_pseudo_bytes($len);
最后,使用这些随机数据创建密码。因为$random中的每个字符可以是chr(0)直到chr(255),代码使用其序数与$alphabet_length除法后的余数来确保只从字母表中选择字符(注意这样做会偏向随机性):
$alphabet_length = strlen($alphabet);
$password = '';
for ($i = 0; $i < $len; ++$i) {
$password .= $alphabet[ord($random[$i]) % $alphabet_length];
}
或者,通常更好的方法是使用RandomLib和SecurityLib:
use SecurityLib\Strength;
$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new Strength(Strength::MEDIUM));
$password = $generator->generateString(12, $alphabet);
只使用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))))))
这将创建一个20个字符的十六进制字符串:
$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars
在PHP 7 (random_bytes())中:
$string = base64_encode(random_bytes(10)); // ~14 characters, includes /=+
// or
$string = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(32))), 0, 32); // 32 characters, without /=+
// or
$string = bin2hex(random_bytes(10)); // 20 characters, only 0-9a-f