常用於產生臨時密碼、API Token、驗證碼、檔名鹽值等場景。以下封裝為可重複使用的函式,支援自訂長度與字元集。
<?php
/**
* 產生隨機字串
* @param int $length 字串長度,預設 6
* @param string $charset 字元集,預設排除 0/O, 1/I/l 等易混淆字元
* @return string
*/
function randStr(int $length = 6, string $charset = ''): string {
if ($charset === '') {
// 預設字元集:大小寫字母(去除易混淆) + 數字(去除0,1) + 符號
$charset = 'ABDEFGHJKLMNPQRSTVWXYabdefghijkmnpqrstvwxy23456789#%*';
}
$maxIdx = strlen($charset) - 1;
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $charset[mt_rand(0, $maxIdx)];
}
return $result;
}
// 使用範例
echo randStr(); // 6 碼預設字元集
echo randStr(10); // 10 碼
echo randStr(32, '0123456789abcdef'); // 32 碼十六進位
?>
若需密碼學安全隨機性 (如 Session ID、加密金鑰、重設密碼 Token),請改用 random_bytes() + Base64/HEX 編碼:
<?php
function randStrSecure(int $bytes = 16, string $encoding = 'base64url'): string {
$bytes = random_bytes($bytes);
return match ($encoding) {
'hex' => bin2hex($bytes),
'base64' => base64_encode($bytes),
'base64url' => rtrim(strtr(base64_encode($bytes), '+/', '-_'), '='),
default => throw new InvalidArgumentException('Unsupported encoding'),
};
}
// 範例:產生 32 位元組 (256 bits) URL-safe Base64 Token
$token = randStrSecure(32); // 約 43 字元
?>
| 場景 | 推薦函式 | 理由 |
|---|---|---|
| 一般唯一代碼、檔名、顯示用 Token | randStr() (mt_rand) | 速度快、字元集可控、可讀性佳 |
| Session ID、CSRF Token、密碼重設連結、API 金鑰 | randStrSecure() (random_bytes) | 密碼學安全、不可預測、防暴力破解 |
| 舊版 PHP (< 7.0) 需安全隨機 | openssl_random_pseudo_bytes() | 相容舊版,需檢查 $crypto_strong |
rand() 或 mt_rand() 產生安全敏感值:兩者皆為偽隨機,種子可預測。time()、microtime()、uniqid() 作為 Token:熵極低,極易衝突與猜測。依用途選對函式,兼顧安全與可用性。