产生随机码

2017-01-12 15:32:05

产生随机密码
 function   Randstr($len=6)   //多少们的密码  
  {  
  $chars='abcdefghijklmnopqrstuvwxyz0123456789';   //   你的密码里用什么构成  
  mt_srand((double)microtime()*1000000*getmypid());   //   seed   the   random   number   generater   (must   be   done)    
  $password='';    
  while(strlen($password)<$len)    
  $password.=substr($chars,(mt_rand()%strlen($chars)),1);    
  return   $password;    
  }
  echo Randstr(6);
//精简版
function   Randstr($len=6)    
    {  
     $chars='abcdefghijklmnopqrstuvwxyz0123456789';      
     $password='';    
     while(strlen($password)<$len)    
     $password.=$chars{rand(0,35)};    
     return   $password;    
    }
    $pword = Randstr(6);
//全面版
产生随机字串,可用来自动生成密码。
特点:
1. 可以指定密码包含数字或字符,默认为混和模式
2. 指定随意密码长度,默认长度为6位

 

代码如下:
#-------------------------------------------
# 产生随机字串,可用来自动生成密码
# 默认长度6位 字母和数字混合
# $format ALL NUMBER CHAR 字串组成格式
#-------------------------------------------
 function randStr($len=6,$format='ALL') {
 switch($format) {
 case 'ALL':
 $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break;
 case 'CHAR':
 $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
 case 'NUMBER':
 $chars='0123456789'; break;
 default :
 $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
 break;
 }
 mt_srand((double)microtime()*1000000*getmypid());
 $password="";
 while(strlen($password)<$len)
    $password.=substr($chars,(mt_rand()%strlen($chars)),1);
 return $password;
 }

//整理后
function rand_pwd($len=6,$format='ALL')
  {
   switch($format)
   {
    case 'ALL':
     $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabckefghijklmnopqrstuvwxyz0123456789";
     break;
    case 'CHAR':
     $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabckefghijklmnopqrstuvwxyz";
     break;
    case 'NUM':
     $chars = "0123456789";
     break;
   }
   $password = '';
   while(strlen($password) < $len)
   $password .= $chars{rand(0,strlen($chars))};
   return $password;
  }

发表评论:

Powered by PHP 学习者(mail:517730729@qq.com)

原百度博客:http://hi.baidu.com/ssfnadn

备案号:闽ICP备17000564号-1

开源中国 PHPCHINA