Random Password Generator PHP Class


/ Published in: PHP
Save to your folder(s)

I rewrote [this snippet](http://snipplr.com/view/15402/php-password-generator/).

Usage:

$password1 = new Password;
$password2 = new Password;

echo '<p>' . $password1->generate() . '</p>';
echo '<p>' . $password2->generate(array('length' => 50)) . '</p>';


Copy this code and paste it in your HTML
  1. <?php
  2. /**
  3. * Generate a random password
  4. */
  5. class Password
  6. {
  7. /**
  8. * Generate the new password
  9. *
  10. * @access public
  11. * @param array $params
  12. * @return string
  13. **/
  14. public function generate($params = array())
  15. {
  16.  
  17. $length = (!array_key_exists('length', $params)) ? 15 : $params['length'];
  18. $use_lower = (!array_key_exists('use_lower', $params)) ? TRUE : $params['use_lower'];
  19. $use_upper = (!array_key_exists('use_upper', $params)) ? TRUE : $params['use_upper'];
  20. $use_number = (!array_key_exists('use_number', $params)) ? TRUE : $params['use_number'];
  21. $use_custom = (!array_key_exists('use_custom', $params)) ? '-_()' : $params['use_custom'];
  22.  
  23. $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  24. $lower = "abcdefghijklmnopqrstuvwxyz";
  25. $number = "0123456789";
  26.  
  27. $seed_length = 0;
  28. $seed = '';
  29.  
  30. if($use_upper === TRUE){
  31. $seed_length += 26;
  32. $seed .= $upper;
  33. }
  34. if($use_lower === TRUE){
  35. $seed_length += 26;
  36. $seed .= $lower;
  37. }
  38. if($use_number === TRUE){
  39. $seed_length += 10;
  40. $seed .= $number;
  41. }
  42. if(!empty($use_custom)){
  43. $seed_length +=strlen($use_custom);
  44. $seed .= $use_custom;
  45. }
  46. for($i = 1; $i <= $length; $i++){
  47. $password .= $seed{rand(0,$seed_length-1)};
  48. }
  49. return $password;
  50. } // End of generate
  51. } // End of Class Password
  52.  
  53. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.