如使用者註冊生成隨機密碼,使用者重置密碼也需要生成乙個隨機的密碼。隨機密碼也就是一串固定長度的字串,文章整理了幾種生成隨機字串的方法。
方法一1、在33 – 126中生成乙個隨機整數,如35。
2、將35轉換成對應的ascii碼字元,如35對應#。
3、重複以上1、2步驟n次,連線成n位的密碼。
該演算法主要用到了兩個函式,mt_rand ( int $min , int $max )函式用於生成隨機整數,其中 $min – $max 為 ascii 碼的範圍,這裡取 33 -126 ,可以根據需要調整範圍,如ascii碼表中 97 – 122 位對應 a – z 的英文本母,具體可參考 ascii碼表; chr ( int $ascii )函式用於將對應整數 $ascii 轉換成對應的字元。
function create_password($pw_length =
$randpwd = 」;
for ($i = 0; $i < $pw_length; $i++)
$randpwd .= chr(mt_rand(33, 126));
return $randpwd;
// 呼叫該函式,傳遞長度引數$pw_length = 6
echo create_password(6);
方法二1、預置乙個的字串 $chars ,包括 a – z,a – z,0 – 9,以及一些特殊字元。
2、在 $chars 字串中隨機取乙個字元。
3、重複第二步n次,可得長度為n的密碼。
function generate_password( $length = 8 ) <>~`+=,.;:/?|';
$password = 」;
for ( $i = 0; $i < $length; $i++ )
// 這裡提供兩種字元獲取方式
// 第一種是使用 substr 擷取$chars中的任意一位字元;
// 第二種是取字元陣列 $chars 的任意元素
// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
return $password;
方法三1、預置乙個的字元陣列 $chars ,包括 a – z,a – z,0 – 9,以及一些特殊字元。
2、通過array_rand()從陣列$chars中隨機選出$length個元素。
3、根據已獲取的鍵名陣列 $keys,從陣列$chars取出字元拼接字串。該方法的缺點是相同的字元不會重複取。
function make_password( $length = 8 )
// 密碼字符集,可任意新增你需要的字元
$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′, 『!',
// 在 $chars 中隨機取 $length 個陣列元素鍵名
$keys = ($chars, $length);
$password = 」;
for($i = 0; $i < $length; $i++)
// 將 $length 個陣列元素連線成字串
$password .= $chars[$keys[$i]];
return $password;
時間效率對比
我們使用以下php**,計算上面的3 個隨機密碼生成函式生成6 位密碼的執行時間,進而對他們的時間效率進行乙個簡單的對比。最終得出的結果是:
方法一:9.8943710327148e-5 秒
方法二:9.6797943115234e-5 秒
方法三:0.00017499923706055 秒可以看出方法一和方法二的執行時間都差不多,而方法三的執行時間稍微長了點。
通過比較三種方法的實現過程,時間效率對比,學習了php生成隨機字串的三種方法,希望可以對大家今後的學習有所幫助。
PHP生成隨機數
function getrandstr length return randstr number getrandstr 6 echo number function make password length 8 在 chars 中隨機取 length 個陣列元素鍵名 keys array rand ...
php生成隨機密碼
隨機密碼生成 post number 0 數字 0 不啟用 1 啟用 post lowercase 0 小寫字母 post uppercase 0 大寫字母 post punctuation 1 特殊符號 post repeat 0 字元 1重複 0不重複 post length 31 密碼長度 p...
php生成隨機數
生成1 10之間的隨機數,不重複。方法一 用shuffle函式。arr range 1,10 shuffle arr foreach arras values 方法二 用array unique函式.arr array while count arr 10 echoimplode arr 方法三 用...