直接上代碼:
function getRandomString($len, $chars=null) { if (is_null($chars)) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; } mt_srand(10000000*(double)microtime()); for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) { $str .= $chars[mt_rand(0, $lc)]; } return $str; }
例如隨機生成 6 位 字母和數字組合
只需調用函數 並傳參6即可。
echo getRandomString(6);
如果僅僅是生成小寫字母你可以使用類似方法
echo chr(mt_rand(65, 90);
大寫字母
echo chr(mt_rand(97, 122));