Advertisements

Generate a random password in PHP

Here’s a code snippet that will quickly generate a random password, using PHP. You can specify the characters set and the number of characters.

function generatePassword($length = 6, $chars = '23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ')
{
  $password = '';
  $char_length = strlen($chars);
  for ($i = 0; $i < $length; $i++)
  {
    $num = rand() % $char_length;
    $password .= $chars[$num];
  }
  return $password;
}

Comments are welcome, as always. Have a faster way or a leaner function? Feel free to share!

Advertisements

,