随机密码生成器PHP类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了随机密码生成器PHP类相关的知识,希望对你有一定的参考价值。

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>';
  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. ?>

以上是关于随机密码生成器PHP类的主要内容,如果未能解决你的问题,请参考以下文章

PHP 随机密码生成器Shell脚本 - 基于PHP类+ SHA1

随机密码生成器Shell脚本-基于PHP类+SHA1

php随机密码函数的实例代码

php生成随机密码(php自定义函数)转自先锋教程网

PHP 代码片段

21个常用代码片段