PHP: Temporary Random Password Generator

Sometimes, you need to generate a temporary password for a new user. Something that meets your security requirements, and is painful enough to make the user change it as soon as they log on. I've got just the ticket.

function genPassword ($length = 8)
{
  // given a string length, returns a random password of that length
  $password = "";
  // define possible characters
  $possible = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $i = 0;
  // add random characters to $password until $length is reached
  while ($i < $length) {
    // pick a random character from the possible ones
    $char =. substr($possible, mt_rand(0, strlen($possible)-1), 1);
    // increment counter
    $i++;
  }
  return $password;
}

To call it, do something like this:

  // e.g. for a password 5 characters long
  $newpass = genPassword(5);
  print "Your new password is " . $newpass . "!";

Add or remove characters to the "$possible" string to change the make up of the password. You can remove look-alike characters like "O" and "0" to make things a little easier. Add spaces, periods, and multi-key combo characters if you don't like your users (lets see how they'd handle an umlaut!).

Tags: 

Comments

Hey, first of all thanks, this is great. Exactly what I was looking for. Just wanted to let you know about a typo I found that will return an error when calling the function. You have "generatePassword" when calling the function, but "genPassword" when it.

Fixed.

It could be more secure and faster if you remove the lines that check if the character already exists.

If you take your algorithm with an 8 character string there are 1.3632589e+14 possible combinations but if you remove the check for already existing character there will be 2.1834011e+14 possible combinations and it will have exactly $length passes so it could be faster.

Just thought I would mention it.

Thanks for the algorithm.

You're right. I've deleted that part form the sample.

you need fix like this

#your code

$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

#fixed code

$password .= substr($possible, mt_rand(0, strlen($possible)-1), 1);

thank you for.

Yet another great catch from my astute readers.