当前位置:Gxlcms > PHP教程 > php自定义函数生成随机密码实例详解

php自定义函数生成随机密码实例详解

时间:2021-07-01 10:21:17 帮助过:23人阅读

如果要做到安全密码与用户名都随机我有一个朋友做服务器的登录密码与用户名就是使用了phpmyadmin随机生成密码功能来做的,与其用phpmyadmin不如自己做了,下文整理了一些关于php随机密码生成的自定义函数供大家参考.

可以指定生成的字符串长度,代码如下:

  1. function rand_str($length, $max=FALSE)
  2. {
  3. if (is_int($max) && $max > $length)
  4. {
  5. $length = mt_rand($length, $max);
  6. }
  7. $output = '';
  8. for ($i=0; $i<$length; $i++)
  9. {
  10. $which = mt_rand(0,2);
  11. if ($which === 0)
  12. {
  13. $output .= mt_rand(0,9);
  14. }
  15. elseif ($which === 1)
  16. {
  17. $output .= chr(mt_rand(65,90));
  18. }
  19. else
  20. {
  21. $output .= chr(mt_rand(97,122));
  22. }
  23. }
  24. return $output;
  25. }

调用实例:$randstr = rand_str(16);

生成随机字符串的函数,代码如下:

  1. <?php
  2. /**
  3. * 产生随机字符串
  4. *
  5. * 产生一个指定长度的随机字符串,并返回给用户
  6. *
  7. * @access public
  8. * @param int $len 产生字符串的位数
  9. * @return string
  10. */
  11. function randStr($len=6) {
  12. $chars='ABDEFGHJKLMNPQRSTVWXYabdefghijkmnpqrstvwxy23456789#%*'; // characters to build the password from
  13. mt_srand((double)microtime()*1000000*getmypid()); // seed the random number generater (must be done)
  14. $password='';
  15. while(strlen($password)<$len)
  16. $password.=substr($chars,(mt_rand()%strlen($chars)),1);
  17. return $password;
  18. }
  19. ?>

创建字符池.

  1. function randomkeys($length)
  2. {
  3. $pattern = '1234567890abcdefghijklmnopqrstuvwxyz
  4. ABCDEFGHIJKLOMNOPQRSTUVWXYZ,./&amp;l
  5. t;&gt;?;#:@~[]{}-_=+)(*&amp;^%$?!'; //字符池
  6. for($i=0; $i<$length; $i++)
  7. {
  8. $key .= $pattern{mt_rand(0,35)}; //生成php随机数
  9. }
  10. return $key;
  11. }
  12. echo randomkeys(8);

无需创建字符池

  1. function randomkeys($length)
  2. {
  3. $output='';
  4. for ($a = 0; $a < $length; $a++) {
  5. $output .= chr(mt_rand(35, 126)); //生成php随机数
  6. }
  7. return $output;
  8. }
  9. echo randomkeys(8);

随机用户名和随机密码例子:

  1. //随机生成用户名(长度6-13)
  2. function create_password($pw_length = 4){
  3. $randpwd = '';
  4. for ($i = 0; $i < $pw_length; $i++){
  5. $randpwd .= chr(mt_rand(33, 126));
  6. }
  7. return $randpwd;
  8. }
  9. function generate_username( $length = 6 ) {
  10. // 密码字符集,可任意添加你需要的字符
  11. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
  12. $password = '';
  13. for ( $i = 0; $i < $length; $i++ )
  14. {
  15. // 这里提供两种字符获取方式
  16. // 第一种是使用substr 截取$chars中的任意一位字符;
  17. // 第二种是取字符数组$chars 的任意元素
  18. // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  19. $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
  20. }
  21. return $password;
  22. }
  23. //调用
  24. $userId = 'user'.generate_username(6);
  25. $pwd = create_password(9);

以上就是php自定义函数生成随机密码实例详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行