自动生成密码,最多生成n个值并显示在新行中

时间:2018-08-08 00:21:19

标签: php arrays

我有一个自动生成密码的代码,我想生成40次随机密码并将其显示在新行中。

$num = 0;
while($num != 40){
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
        }
print_r ($pass);
echo implode("<br>",$pass);
$num++;
}

代码将每个字符串的数组分隔为新行。我需要显示一个包含8个字符的字符串,每行最多显示40次。

2 个答案:

答案 0 :(得分:2)

您正在寻找echo implode("<br>",$pass);而不是echo implode($pass) . "<br />";

$num = 0;
while($num != 40){
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
        }
    print_r ($pass);
    echo implode($pass) . "<br />";
    $num++;
}

可以在 here 上看到它。

请注意,rand() not a cryptographically secure pseudorandom number generator ,不应用于生成密码。对于此类任务,建议您检出一些 these answers 。请记住,在暴力破解方面,长度远比复杂度重要,因此您可能还希望从8开始使用长度。

答案 1 :(得分:-1)

function random_pass( $length = 8 ) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $password = substr( str_shuffle( $chars ), 0, $length );
    return $password;
}
$num = 0;
while($num <= 40){
    $pass = random_pass();
    echo $pass. '<br>';
    $num++;
}