我试图在php中生成一个随机密码。
但是我得到的都是'a'返回类型是数组类型,我希望它是字符串。对如何修改代码有什么想法吗?
谢谢。
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
for ($i = 0; $i < 8; $i++) {
$n = rand(0, count($alphabet)-1);
$pass[$i] = $alphabet[$n];
}
return $pass;
}
Generates a strong password of length 8 containing at least one lower case letter, one uppercase letter, one digit, and one special character. You can change the length in the code too.
function checkForCharacterCondition($string) {
return (bool) preg_match('/(?=.*([A-Z]))(?=.*([a-z]))(?=.*([0-9]))(?=.*([~`\!@#\$%\^&\*\(\)_\{\}\[\]]))/', $string);
}
$j = 1;
function generate_pass() {
global $j;
$allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_{}[]';
$pass = '';
$length = 8;
$max = mb_strlen($allowedCharacters, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pass .= $allowedCharacters[random_int(0, $max)];
}
if (checkForCharacterCondition($pass)){
return '<br><strong>Selected password: </strong>'.$pass;
}else{
echo 'Iteration '.$j.': <strong>'.$pass.'</strong> Rejected<br>';
$j++;
return generate_pass();
}
}
echo generate_pass();
这是基于本页的另一个答案,https://stackoverflow.com/a/21498316/525649
这个答案只生成十六进制字符,0-9,a-f。对于一些看起来不像hex的东西,试试这个:
str_shuffle(
rtrim(
base64_encode(bin2hex(openssl_random_pseudo_bytes(5))),
'='
).
strtoupper(bin2hex(openssl_random_pseudo_bytes(7))).
bin2hex(openssl_random_pseudo_bytes(13))
)
Base64_encode返回更广泛的字母数字字符
Rtrim有时会在结尾删除=
例子:
32 efvfgdg891be5e7293e54z1d23110m3zu3fmjb30z9a740ej0jz4
b280R72b48eOm77a25YCj093DE5d9549Gc73Jg8TdD9Z0Nj4b98760
051年b33654c0eg201cfw0e6na4b9614ze8d2fn49e12y0zy557aucb8
y67Q86ffd83G0z00M0Z152f7O2ADcY313gD7a774fc5FF069zdb5b7
对于为用户创建界面来说,这不是很可配置的,但对于某些目的来说,这是可以的。增加字符数,以弥补特殊字符的不足。
下面是另一个密码生成器代码片段。
控制长度,数字和特殊字符计数和列表。
其他解决方案的一个问题是,它们没有包含重复字符的选项。而下面的脚本也可以做到这一点。
$length = random_int(30, 40);
$pass = [];
$lowers = range('a', 'z');
$uppers = range('A', 'Z');
$digits = range('0', '9');
$specials = ['.', '-', '_', '^', '#', '(', ')'];
$specialCount = random_int(1, 5);
$digitCount = random_int(1, 9);
for ($i = 0; $i < $length - $specialCount - $digitCount; $i++) {
$pass[] = random_int(1, PHP_INT_MAX) % 2 == 0 ? $uppers[array_rand($uppers)] : $lowers[array_rand($lowers)];
}
for ($i = 0; $i < $specialCount; $i++) {
$pass[] = $specials[array_rand($specials)];
}
for ($i = 0; $i < $digitCount; $i++) {
$pass[] = $digits[array_rand($digits)];
}
shuffle($pass)
$pass = implode('', $pass);