Simple helper function to generate a password for use in, say, a user account. Saves people the fuss and bother of coming up with their own. Takes a single parameter to determine the length of the password. Defaults to 8 chars.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*--------------------------------------------------------------------------*\
  Function:    generate_password
  Parameters: length - any integer value, specifying the length of the password.
  Returns:      the password. Duh.
\*--------------------------------------------------------------------------*/

function generate_password($length = 8)
{
  $password = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz";
  $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);

    // we don't want this character if it's already in the password
    if (!strstr($password, $char)) {
      $password .= $char;
      $i++;
    }
  }

  return $password;
}