在 PHP 開發中,生成隨機字串是常見需求,例如驗證碼、臨時密碼或唯一標識符。本文分享一個簡潔高效的自定義函數 randStr(),可按指定長度產生包含大小寫字母與數字的隨機字串。
<?php
/**
* 產生隨機字串,適用於驗證碼等場景
* @param int $length 字串長度,預設 5
* @return string 隨機字串
*/
function randStr($length = 5) {
$charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$maxIndex = strlen($charset) - 1;
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $charset[mt_rand(0, $maxIndex)];
}
return $result;
}
// 測試:產生 6 位隨機字串
$randomCode = randStr(6);
echo $randomCode; // 輸出範例:aB3fG9
?>
rand() 速度更快、隨機度更高,適合生成非加密用途的隨機值。$length 控制輸出長度,預設為 5,可依需求調整。此函數可直接用於:
若需加密級別的隨機性(如密碼重設 Token),建議改用 random_bytes() 或 openssl_random_pseudo_bytes()。