首页 > 语言 > PHP > 正文

php随机生成字符串程序方法总结

2024-09-04 11:48:34
字体:大 中 小
来源:转载
供稿:网友

在开发中我们可以会经常碰到需要生成系统随机密码或者是登陆验证码之类的,这些数字我们肯定需要随机生成的不能定义的,下面我来总结了一些常用的在php中生成随机字符的代码,有需要的朋友可参考.

随机生成数数字

mt_rand()函数,代码如下:

$num = mt_rand(0,9999999);

但如果我想随机生成字符串怎么操作,网站找到一个方法,代码如下:

  1. function random($length) {  
  2.      srand(date("s"));  
  3.      $possible_charactors = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
  4.      $string = "";  
  5.      while(strlen($string)<$length) {  
  6.           $string .= substr($possible_charactors,(rand()%(strlen($possible_charactors))),1);  
  7.      }  
  8.      return($string);  
  9. } 

例2,代码如下:

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

例3,代码如下:

  1. <?php 
  2. // 说明:php 中生成随机字符串的方法  
  3. // 整理:http://www.Vevb.com  
  4. function genRandomString($len) 
  5. { 
  6.     $chars = array( 
  7.         "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",   
  8.         "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",   
  9.         "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",   
  10.         "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",   
  11.         "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",   
  12.         "3", "4", "5", "6", "7", "8", "9" 
  13.     ); 
  14.     $charsLen = count($chars) - 1; 
  15.     shuffle($chars);    // 将数组打乱  
  16.        
  17.     $output = ""; 
  18.     for ($i=0; $i<$len; $i++) 
  19.     { 
  20.         $output .= $chars[mt_rand(0, $charsLen)]; 
  21.     } 
  22.     return $output; 
  23. } 
  24. $str = genRandomString(25); 
  25. $str .= "<br />"; 
  26. $str .= genRandomString(25); 
  27. $str .= "<br />"; 
  28. $str .= genRandomString(25); 
  29. echo $str; 
  30. ?>  

注:传入的参数是你想要生成的随机字符串的长度.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表