Welcome, guest | Sign In | My Account | Store | Cart

Improved version of make_password submitted by Shane Caraveo. This one adds options to use upper case characters, numerics and special characters.

PHP, 29 lines
 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
27
28
29
function make_password($length,$strength=0) {
  $vowels = 'aeiouy';
  $consonants = 'bdghjlmnpqrstvwxz';
  if ($strength & 1) {
    $consonants .= 'BDGHJLMNPQRSTVWXZ';
  }
  if ($strength & 2) {
    $vowels .= "AEIOUY";
  }
  if ($strength & 4) {
    $consonants .= '0123456789';
  }
  if ($strength & 8) {
    $consonants .= '@#$%^';
  }
  $password = '';
  $alt = time() % 2;
  srand(time());
  for ($i = 0; $i < $length; $i++) {
    if ($alt == 1) {
      $password .= $consonants[(rand() % strlen($consonants))];
      $alt = 0;
    } else {
        $password .= $vowels[(rand() % strlen($vowels))];
      $alt = 1;
    }
  }
  return $password;
}

After seeing the comments regarding password security I amended Shane's original code to include a strength option. This is a bit mask of the various options: 1 adds in upper case consonants, 2 adds in upper case vowels, 4 adds in numbers and 8 adds in special characters. make_password(8,3); would geberate an 8 character password with upper and lower consonants and vowels. make_password(8,5); would generate an 8 character password with upper case consonants and numbers. It can still generate a valid dictionary entry at random (unless numbers and special characters are included)

1 comment

Gareth Palidwor 19 years, 6 months ago  # | flag

better time resolution gives better randomness. Minor tweak:

list($microtime,$fulltime) = split("\s+",microtime()); $microtime = $microtime * 100000000; srand($microtime); $alt = $microtime % 2;

With the settings in the script as is, it will give the same password every time it is called during the same second. Minor security hole. Using the microsecond resolution time to seed the random number is better.

Created by Alan Prescott on Fri, 29 Nov 2002 (MIT)
PHP recipes (51)
Alan Prescott's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks