Protik
Protik

Reputation: 11

How to create Random Password Generator using PHP?

This can generate random password.

<?php
function randomPassword() {
    $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $pass = array();
    $alphaLength = strlen($alphabet) - 1;
    for ($i = 0; $i < 26; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass);
}

echo randomPassword();
?>

But I want to save this password in passwords.txt file. And next time when create a new password, it will check this password is in that passwords.txt or not. And than echo. If the password is already have, then go to the else condition and do it again. How can I write this code?

Upvotes: 1

Views: 3168

Answers (1)

Soatok Dreamseeker
Soatok Dreamseeker

Reputation: 53

  1. You want to use random_int(), not rand().
  2. There's a function called file_put_contents() that lets you write to a file. It even has an append mode.

For example:

<?php
declare(strict_types=1);

function randomPassword(int $passwordLength = 26): string {
   $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   $pass = array();
    $alphaLength = strlen($alphabet) - 1;
    for ($i = 0; $i < $passwordLength; $i++) {
        $n = random_int(0, $alphaLength);
        $pass[] = $alphabet[$n];
    }
    return implode($pass);
}

$random = randomPassword();
file_put_contents(
    'passwords.txt',
    $random . "\n",
    FILE_APPEND
);

Upvotes: 1

Related Questions