方法一:shuffle函数(打乱数组)和mt_rand函数(生成随机数,比rand速度快四倍)
/** 获得随机字符串 @param $len 需要的长度 @param $special 是否需要特殊符号 @return string 返回随机字符串 */ function getRandomStr($len, $special=true){ $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" ); if($special){ $chars = array_merge($chars, array( "!", "@", "#", "$", "?", "|", "{", "/", ":", ";", "%", "^", "&", "*", "(", ")", "-", "_", "[", "]", "}", "<", ">", "~", "+", "=", ",", "." )); } $charsLen = count($chars) - 1; shuffle($chars); //打乱数组顺序 $str = ''; for($i=0; $i<$len; $i++){ $str .= $chars[mt_rand(0, $charsLen)]; //随机取出一位 } return $str; }
方法二、str_shuffle函数(打乱字符串顺序)和mt_rand函数
//取随机10位字符串 $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm"; $name=substr(str_shuffle($strs),mt_rand(0,strlen($strs)-11),10); echo $name;
方法三、md5(),uniqid(),microtime()生成唯一的32位字符串
$uniqid = md5(uniqid(microtime(true),true)); //microtime(true) 返回系统当前时间戳的毫秒数
其他方法:
/**
* 方法一:获取随机字符串
* @param number $length 长度
* @param string $type 类型
* @param number $convert 转换大小写
* @return string 随机字符串
*/
function random($length = 6, $type = 'string', $convert = 0)
{
$config = array(
'number' => '1234567890',
'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
);
if (!isset($config[$type]))
$type = 'string';
$string = $config[$type];
$code = '';
$strlen = strlen($string) - 1;
for ($i = 0; $i < $length; $i++) {
$code .= $string{mt_rand(0, $strlen)};
}
if (!empty($convert)) {
$code = ($convert > 0) ? strtoupper($code) : strtolower($code);
}
return $code;
}
/**
* 方法二:获取随机字符串
* @param int $randLength 长度
* @param int $addtime 是否加入当前时间戳
* @param int $includenumber 是否包含数字
* @return string
*/
function rand_str($randLength = 6, $addtime = 1, $includenumber = 0)
{
if ($includenumber) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
} else {
$chars = 'abcdefghijklmnopqrstuvwxyz';
}
$len = strlen($chars);
$randStr = '';
for ($i = 0; $i < $randLength; $i++) {
$randStr .= $chars[mt_rand(0, $len - 1)];
}
$tokenvalue = $randStr;
if ($addtime) {
$tokenvalue = $randStr . time();
}
return $tokenvalue;
}