方法一:
/**
* @desc im:取得随机字符串
* @param (int)$length = 32 #随机字符长度,默认为32
* @param (int)$mode = 0 #随机字符类型,0为大小写英文和数字,1为数字,2为小写字母,3为大写字母,4为大小写字母,5为大写字母和数字,6为小写字母和数字
* return 返回:取得的字符串
*/
function get_random_code ($length = 32, $mode = 0)
{
switch ($mode) {
case "1":
$str = "1234567890";
break;
case "2":
$str = "abcdefghijklmnopqrstuvwxyz";
break;
case "3":
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
break;
case "4":
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
break;
case "5":
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
break;
case "6":
$str = "abcdefghijklmnopqrstuvwxyz1234567890";
break;
default:
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
break;
}
$result="";
$l=strlen($str);
for($i=0;$i < $length;$i++){
$num = rand(0, $l-1); //如果$i不减1,将不一定生成4位数, 因为$num = rand(0,10).会随机产生10,$str[10] 为空
$result .= $str[$num];
}
return $result;
}
方法二:
< ?php
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(16);
$str .= "
";
$str .= genRandomString(16);
echo $str;
?>