PHP - Password generator


SUBMITTED BY: Guest

DATE: June 13, 2013, 7:58 p.m.

FORMAT: PHP

SIZE: 1.9 kB

HITS: 1088

  1. <?PHP
  2. // Generates a strong password of N length containing at least one lower case letter,
  3. // one uppercase letter, one digit, and one special character. The remaining characters
  4. // in the password are chosen at random from those four sets.
  5. //
  6. // The available characters in each set are user friendly - there are no ambiguous
  7. // characters such as i, l, 1, o, 0, etc. This, coupled with the $add_dashes option,
  8. // makes it much easier for users to manually type or speak their passwords.
  9. //
  10. // Note: the $add_dashes option will increase the length of the password by
  11. // floor(sqrt(N)) characters.
  12. function generateStrongPassword($length = 9, $add_dashes = false, $available_sets = 'luds')
  13. {
  14. $sets = array();
  15. if(strpos($available_sets, 'l') !== false)
  16. $sets[] = 'abcdefghjkmnpqrstuvwxyz';
  17. if(strpos($available_sets, 'u') !== false)
  18. $sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ';
  19. if(strpos($available_sets, 'd') !== false)
  20. $sets[] = '23456789';
  21. if(strpos($available_sets, 's') !== false)
  22. $sets[] = '!@#$%&*?';
  23. $all = '';
  24. $password = '';
  25. foreach($sets as $set)
  26. {
  27. $password .= $set[array_rand(str_split($set))];
  28. $all .= $set;
  29. }
  30. $all = str_split($all);
  31. for($i = 0; $i < $length - count($sets); $i++)
  32. $password .= $all[array_rand($all)];
  33. $password = str_shuffle($password);
  34. if(!$add_dashes)
  35. return $password;
  36. $dash_len = floor(sqrt($length));
  37. $dash_str = '';
  38. while(strlen($password) > $dash_len)
  39. {
  40. $dash_str .= substr($password, 0, $dash_len) . '-';
  41. $password = substr($password, $dash_len);
  42. }
  43. $dash_str .= $password;
  44. return $dash_str;
  45. }

comments powered by Disqus