在開發中我們可以會經常碰到需要生成系統隨機密碼或者是登陸驗證碼之類的,這些數字我們肯定需要隨機生成的不能定義的,下面我來總結了一些常用的在php中生成隨機字符的代碼,有需要的朋友可參考.
隨機生成數數字
mt_rand()函數,代碼如下:
$num = mt_rand(0,9999999);
但如果我想隨機生成字符串怎么操作,網站找到一個方法,代碼如下:
- function random($length) {
- srand(date("s"));
- $possible_charactors = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- $string = "";
- while(strlen($string)<$length) {
- $string .= substr($possible_charactors,(rand()%(strlen($possible_charactors))),1);
- }
- return($string);
- }
例2,代碼如下:
- function random_string($length, $max=FALSE)
- {
- if (is_int($max) && $max > $length)
- {
- $length = mt_rand($length, $max);
- }
- $output = '';
- for ($i=0; $i<$length; $i++)
- {
- $which = mt_rand(0,2);
- if ($which === 0)
- {
- $output .= mt_rand(0,9);
- }
- elseif ($which === 1)
- {
- $output .= chr(mt_rand(65,90));
- }
- else
- {
- $output .= chr(mt_rand(97,122));
- }
- }
- return $output;
- }
例3,代碼如下:
- <?php
- // 說明:php 中生成隨機字符串的方法
- // 整理:http://www.companysz.com
- function genRandomString($len)
- {
- $chars = array(
- "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
- "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
- "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
- "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
- "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
- "3", "4", "5", "6", "7", "8", "9"
- );
- $charsLen = count($chars) - 1;
- shuffle($chars); // 將數組打亂
- $output = "";
- for ($i=0; $i<$len; $i++)
- {
- $output .= $chars[mt_rand(0, $charsLen)];
- }
- return $output;
- }
- $str = genRandomString(25);
- $str .= "<br />";
- $str .= genRandomString(25);
- $str .= "<br />";
- $str .= genRandomString(25);
- echo $str;
- ?>
注:傳入的參數是你想要生成的隨機字符串的長度.
新聞熱點
疑難解答