我试图在php中生成一个随机密码。

但是我得到的都是'a'返回类型是数组类型,我希望它是字符串。对如何修改代码有什么想法吗?

谢谢。

function randomPassword() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    for ($i = 0; $i < 8; $i++) {
        $n = rand(0, count($alphabet)-1);
        $pass[$i] = $alphabet[$n];
    }
    return $pass;
}

当前回答

该函数将根据参数中的规则生成密码

function random_password( $length = 8, $characters = true, $numbers = true, $case_sensitive = true, $hash = true ) {

    $password = '';

    if($characters)
    {
        $charLength = $length;
        if($numbers) $charLength-=2;
        if($case_sensitive) $charLength-=2;
        if($hash) $charLength-=2;
        $chars = "abcdefghijklmnopqrstuvwxyz";
        $password.= substr( str_shuffle( $chars ), 0, $charLength );
    }

    if($numbers)
    {
        $numbersLength = $length;
        if($characters) $numbersLength-=2;
        if($case_sensitive) $numbersLength-=2;
        if($hash) $numbersLength-=2;
        $chars = "0123456789";
        $password.= substr( str_shuffle( $chars ), 0, $numbersLength );
    }

    if($case_sensitive)
    {
        $UpperCaseLength = $length;
        if($characters) $UpperCaseLength-=2;
        if($numbers) $UpperCaseLength-=2;
        if($hash) $UpperCaseLength-=2;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $password.= substr( str_shuffle( $chars ), 0, $UpperCaseLength );
    }

    if($hash)
    {
        $hashLength = $length;
        if($characters) $hashLength-=2;
        if($numbers) $hashLength-=2;
        if($case_sensitive) $hashLength-=2;
        $chars = "!@#$%^&*()_-=+;:,.?";
        $password.= substr( str_shuffle( $chars ), 0, $hashLength );
    }

    $password = str_shuffle( $password );
    return $password;
}

其他回答

你需要strlen($alphabet),而不是常量字母的计数(相当于'alphabet')。

然而,rand并不是一个适合于此目的的随机函数。它的输出可以很容易地预测,因为它隐含地以当前时间作为种子。此外,兰特是不加密安全的;因此,从输出中确定其内部状态相对容易。

相反,从/dev/urandom读取以获得加密随机数据。

下面是另一个密码生成器代码片段。 控制长度,数字和特殊字符计数和列表。

其他解决方案的一个问题是,它们没有包含重复字符的选项。而下面的脚本也可以做到这一点。

$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);

该函数将根据参数中的规则生成密码

function random_password( $length = 8, $characters = true, $numbers = true, $case_sensitive = true, $hash = true ) {

    $password = '';

    if($characters)
    {
        $charLength = $length;
        if($numbers) $charLength-=2;
        if($case_sensitive) $charLength-=2;
        if($hash) $charLength-=2;
        $chars = "abcdefghijklmnopqrstuvwxyz";
        $password.= substr( str_shuffle( $chars ), 0, $charLength );
    }

    if($numbers)
    {
        $numbersLength = $length;
        if($characters) $numbersLength-=2;
        if($case_sensitive) $numbersLength-=2;
        if($hash) $numbersLength-=2;
        $chars = "0123456789";
        $password.= substr( str_shuffle( $chars ), 0, $numbersLength );
    }

    if($case_sensitive)
    {
        $UpperCaseLength = $length;
        if($characters) $UpperCaseLength-=2;
        if($numbers) $UpperCaseLength-=2;
        if($hash) $UpperCaseLength-=2;
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $password.= substr( str_shuffle( $chars ), 0, $UpperCaseLength );
    }

    if($hash)
    {
        $hashLength = $length;
        if($characters) $hashLength-=2;
        if($numbers) $hashLength-=2;
        if($case_sensitive) $hashLength-=2;
        $chars = "!@#$%^&*()_-=+;:,.?";
        $password.= substr( str_shuffle( $chars ), 0, $hashLength );
    }

    $password = str_shuffle( $password );
    return $password;
}

有一个简短的解决方案(php 8.1):

$dict = array_merge(
    ...array_map(
        fn(array $d): array => range(ord($d[0]), ord($d[1])),
        [["0", "9"], ["a", "z"], ["A", "Z"]]
    )
); 

$f = fn (int $len): string =>
    join(
        "",
        array_map(
            fn (): string => chr($dict[random_int(0, count($dict) - 1)]),
            range(0, $len)
        )
    ); 

echo $f(12) . PHP_EOL;

一行bash脚本:

PHP -r '$dict = array_merge(…到fn(数组$ d):数组= >范围(奥德($ d[0]),奥德($ d[1])),(“0”,“9”,“一个”、“z”,[“一”、“z”]]));$ f = fn (int len美元):字符串= >加入(“”,到(fn():字符串= >科($ dict [random_int (0, count ($ dict) - 1))),范围(0,len美元)));Echo $f(12)。PHP_EOL;”

这是来自https://stackoverflow.com/a/41077923/5599052的想法

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();