How to generate random password with PHP?

Or is there a software to auto generate random passwords?


Solution 1:

Just build a string of random a-z, A-Z, 0-9 (or whatever you want) up to the desired length. Here's an example in PHP:

function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
}

To optimize, you can define $chars as a static variable or constant in the method (or parent class) if you'll be calling this function many times during a single execution.

Solution 2:

Here's a simple solution. It will contain lowercase letters and numbers.

substr(str_shuffle(strtolower(sha1(rand() . time() . "my salt string"))),0, $PASSWORD_LENGTH);

Here's A stronger solution randomly generates the character codes in the desired character range for a random length within a desired range.

function generateRandomPassword() {
  //Initialize the random password
  $password = '';

  //Initialize a random desired length
  $desired_length = rand(8, 12);

  for($length = 0; $length < $desired_length; $length++) {
    //Append a random ASCII character (including symbols)
    $password .= chr(rand(32, 126));
  }

  return $password;
}