Generate Password Function In PHP

17th November 2008 - 3 minutes read time

I have talked about generating random passwords before. Although that function generated some nice passwords, they perhaps aren't as unique as they ought to be.

This function, take from Webtoolkit creates passwords of different length with varying levels of complexity.

  1. function generatePassword($length=9, $strength=0) {
  2. $vowels = 'aeiu';
  3. $consonants = 'bdghjmnpqrstvxyz';
  4. if ( $strength & 1 ) {
  5. $consonants .= 'BDGHJLMNPQRSTVWXYZ';
  6. }
  7. if ( $strength & 2 ) {
  8. $vowels .= 'AEU';
  9. }
  10. if ( $strength & 4 ) {
  11. $consonants .= '23456789';
  12. }
  13. if ( $strength & 8 ) {
  14. $consonants .= '@#$%';
  15. }
  16.  
  17. $password = '';
  18. $alt = time() % 2;
  19. for ($i = 0; $i < $length; $i++) {
  20. if ($alt == 1) {
  21. $password .= $consonants[(rand() % strlen($consonants))];
  22. $alt = 0;
  23. } else {
  24. $password .= $vowels[(rand() % strlen($vowels))];
  25. $alt = 1;
  26. }
  27. }
  28. return $password;
  29. }

The first parameter is the number of characters that the function should return. The second parameter is a number up to 8 which converts into complexity. The least complex password consists of only lower case consonants. The most complex password consists of upper and lower case letters, as well as numbers and symbols.

You might notice that some of the letters and numbers are missing, this is deliberate. When passwords are generated many of the characters can be very similar. Zero can look like an upper case O and I can look like the number one or a lower case L. Removing these letters stops people getting their passwords wrong and having to reapply for them in the future. Also, many people write down their passwords, even though you shouldn't, and in doing this many characters can also look the same. For example, in a mix of upper and lowercase letters it is difficult to see the difference between an upper and lower case W.

You can run the function like this.

  1. echo generatePassword(8,1); // LareSuSy
  2. echo generatePassword(8,2); // hUsuserU
  3. echo generatePassword(8,3); // MEdEgYze
  4. echo generatePassword(8,4); // tanapa3a
  5. echo generatePassword(8,5); // ary2ugeR
  6. echo generatePassword(8,6); // uqUtebyq
  7. echo generatePassword(8,7); // yRysuNEV
  8. echo generatePassword(8,8); // ygyqyha%

This is just the output that I got from these parameters, a different password is run each time. You should be using level 8 for any system administrator passwords.

Add new comment

The content of this field is kept private and will not be shown publicly.