我试图在php中生成一个随机密码。
但是我得到的都是'a'返回类型是数组类型,我希望它是字符串。对如何修改代码有什么想法吗?
谢谢。
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
for ($i = 0; $i < 8; $i++) {
$n = rand(0, count($alphabet)-1);
$pass[$i] = $alphabet[$n];
}
return $pass;
}
我的答案与上面的一些类似,但我去掉了元音,数字1和0,字母I, j, I, l, O, O, Q, Q, X, X, Y, Y, W, W。原因是:第一个很容易混淆(就像l和1,取决于字体),其余的(从Q开始)是因为它们在我的语言中不存在,所以对于超级终端用户来说可能有点奇怪。字符串仍然足够长。此外,我知道使用一些特殊的标志是理想的,但他们也与一些最终用户相处不好。
function generatePassword($length = 8) {
$chars = '23456789bcdfhkmnprstvzBCDFHJKLMNPRSTVZ';
$shuffled = str_shuffle($chars);
$result = mb_substr($shuffled, 0, $length);
return $result;
}
此外,通过这种方式,我们避免重复相同的字母和数字(不包括匹配情况)
这是我的密码助手
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)
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();