| 函數 | 演算法 | 範圍 | 密碼學安全 | 建議用途 |
|---|---|---|---|---|
rand() | 線性同餘(LCG) | 0 ~ getrandmax() (通常 2^31-1) | ❌ 可預測 | 簡單測試、非安全場景 |
mt_rand() | 梅森旋轉 (MT19937) | 0 ~ mt_getrandmax() (2^31-1) | ❌ 可預測 | 一般模擬、遊戲、抽獎 |
random_int() | 作業系統 CSPRNG | 指定 min/max | ✅ 安全 | 密碼、Token、加密金鑰、OTP |
<?php
// rand / mt_rand
echo rand(10, 100) . "\n";
echo mt_rand(10, 100) . "\n";
// random_int (PHP 7+)
try {
echo random_int(10, 100) . "\n";
} catch (Exception $e) {
echo "熵源不足: " . $e->getMessage();
}
// 產生隨機字串(Token)
function randomToken(int $length = 32): string {
$bytes = random_bytes($length);
return bin2hex($bytes); // 或 base64_encode($bytes)
}
echo randomToken(16); // 32 字元十六進位
<?php
// 固定種子 → 固定序列(可復現,適合測試/模擬)
mt_srand(12345);
echo mt_rand() . "\n"; // 永遠相同
echo mt_rand() . "\n";
// 自動種子(PHP 4.2+ 預設自動,無需呼叫 srand)
// 早期寫法(已過時):
// srand((double)microtime() * 1000000);
注意:現代 PHP (4.2+) 已自動以高熵值播種,**嚴禁手動呼叫 srand()/mt_srand()**,會降低隨機品質甚至造成安全漏洞。
rand() 不夠隨機,要用 srand(microtime()*1e6)」。mt_rand() 適合生成密碼」。random_int()/random_bytes()**。rand(0, 10) 對 11 取模會有微小偏差,random_int() 保證均勻分佈。function generateResetToken(): string {
return bin2hex(random_bytes(32)); // 256 bits entropy
}
function shuffleSecure(array &$arr): void {
for ($i = count($arr) - 1; $i > 0; $i--) {
$j = random_int(0, $i);
[$arr[$i], $arr[$j]] = [$arr[$j], $arr[$i]];
}
}
function weightedRandom(array $weights): int {
$total = array_sum($weights);
$r = random_int(1, $total);
foreach ($weights as $idx => $w) {
$r -= $w;
if ($r <= 0) return $idx;
}
return array_key_last($weights);
}
// 權重 [10, 30, 60] → 索引 0/1/2 機率 10%/30%/60%