我试图在php中生成一个随机密码。
但是我得到的都是'a'返回类型是数组类型,我希望它是字符串。对如何修改代码有什么想法吗?
谢谢。
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
for ($i = 0; $i < 8; $i++) {
$n = rand(0, count($alphabet)-1);
$pass[$i] = $alphabet[$n];
}
return $pass;
}
下面是我对随机密码生成助手的看法。
它确保密码包含数字,大写字母和小写字母,以及至少3个特殊字符。
密码长度为11 ~ 30。
function plainPassword(): string
{
$numbers = array_rand(range(0, 9), rand(3, 9));
$uppercase = array_rand(array_flip(range('A', 'Z')), rand(2, 8));
$lowercase = array_rand(array_flip(range('a', 'z')), rand(3, 8));
$special = array_rand(array_flip(['@', '#', '$', '!', '%', '*', '?', '&']), rand(3, 5));
$password = array_merge(
$numbers,
$uppercase,
$lowercase,
$special
);
shuffle($password);
return implode($password);
}
下面是另一个密码生成器代码片段。
控制长度,数字和特殊字符计数和列表。
其他解决方案的一个问题是,它们没有包含重复字符的选项。而下面的脚本也可以做到这一点。
$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);
这是我的密码助手
class PasswordHelper
{
/**
* generate a secured random password
*/
public static function generatePassword(
int $lowerCaseCount=8,
int $upperCaseCount=8,
int $numberCount=8,
int $specialCount=4
): string
{
$lowerCase = 'abcdefghijklmnopqrstuvwxyz';
$upperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$number = '0123456789';
$special = '!@#$%^&*';
$password = self::getRandom($lowerCase, $lowerCaseCount);
$password .= self::getRandom($upperCase, $upperCaseCount);
$password .= self::getRandom($number, $numberCount);
$password .= self::getRandom($special, $specialCount);
return str_shuffle($password);
}
/**
* get a random string from a set of characters
*/
public static function getRandom($set, $length): string
{
$rand = '';
$setLength = strlen($set);
for ($i = 0; $i < $length; $i++)
{
$rand .= $set[random_int(0, $setLength - 1)];
}
return $rand;
}
}
用法:
PasswordHelper::generatePassword()或PasswordHelper::generatePassword(2,4,5,3)