常見需求如生成驗證碼、臨時密碼、唯一標識等。核心邏輯:定義字符池,循環隨機抽取字符拼接。
<?php
function randomString($len, $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()') {
$str = '';
$maxIndex = strlen($charset) - 1;
for ($i = 0; $i < $len; $i++) {
$str .= $charset[random_int(0, $maxIndex)];
}
return $str;
}
// 使用範例
echo randomString(16); // 預設字符集
echo randomString(8, '0123456789'); // 純數字驗證碼
?>
rand()/srand():不可預測性不足,改用 random_int() (PHP 7+) 或 openssl_random_pseudo_bytes() 獲取加密級隨機數。strlen() 重複調用:預先計算字符池長度。random_int(0, $maxIndex) 保證均勻分佈。若需極低碰撞概率的唯一 ID,推薦組合時間戳與隨機數:
function uniqueId($prefix = '') {
return $prefix . bin2hex(random_bytes(8)) . substr(microtime(), 2, 6);
}
或直接使用 uniqid('', true)(含微秒)。
切勿用此類函數生成加密金鑰、JWT Secret 等高敏感值,請改用 random_bytes()、openssl_random_pseudo_bytes() 或專用庫(如 paragonie/random_compat)。