在一些特殊应用中,需要生成随机字符串,比如生成系统随机密码或者是登陆验证码等,本文介绍的函数能够返回指定长度的随机字符串,默认包含大小写字母和数字,你可以很容易的修改以便符合自己的需要。
自 PHP 4.2.0 起,不再需要用 srand() 或 mt_srand() 函数给随机数发生器播种,之前的版本可以在 mt_rand 之前先运行mt_srand((double)microtime()*1000000) 。
<?php
// 说明:php 中生成随机字符串的方法
// 整理:http://www.CodeBit.cn
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;
?>
注:传入的参数是你想要生成的随机字符串的长度。