0

I have a code from auto generating passwords and i want to produce up to 40 times of random passwords and displaying it into a new line.

$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++;
}

the code separates the array per strings into new line. I need to display a strings with 8 characters up to 40 times per line.

2 Answers2

2

Instead of echo implode("<br>",$pass);, you're looking for 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++;
}

This can be seen working here.

Note that rand() is not a cryptographically secure pseudorandom number generator, and should not be used for password generation. For such tasks, I would recommend checking out some of these answers. Keep in mind that length is far more important than complexity with regards to brute-forcing, so you may also wish to up your lengths from 8.

Obsidian Age
  • 39,491
  • 10
  • 44
  • 66
  • I understand you only touched the line that produces an output, but a tiny warning that `rand` is a poor choice to generate any kind of passwords would be helpful as well (upvoted anyway) PS: kia ora :-) – zerkms Aug 08 '18 at 00:40
  • 1
    I've added a quick note on `rand()`'s weaknesses, and linked to the question that this code appears to be based off of. There's plenty of answers there on more secure password generations -- though password complexity definitely comes second to password length. Kia ora! :) – Obsidian Age Aug 08 '18 at 00:55
-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++;
}
Aditya Gupta
  • 1
  • 1
  • 1
  • 2
    While this code snippet may be the solution, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Narendra Jadhav Aug 08 '18 at 05:47