常見於驗證碼、訂單編號、臨時密碼、API Nonce 等需「固定長度、純數字、重複機率低」的場合。
mt_rand() 區間拼接(最簡潔、效能佳)<?php
// 產生兩段 8 位數字,拼成 16 位
$part1 = mt_rand(10000000, 99999999); // 8 位,首位非 0
$part2 = mt_rand(10000000, 99999999);
$rand16 = $part1 . $part2;
echo $rand16; // 例:3847291056382917
優點:程式碼極短、執行快、分佈均勻。
注意:mt_rand() 非加密安全,勿用於密碼產生。
range() + array_rand() 逐位抽取(教學示範用)<?php
$digits = range(0, 9); // [0,1,2,3,4,5,6,7,8,9]
$result = [];
for ($i = 0; $i < 16; $i++) {
// array_rand 回傳鍵值,這裡鍵值即數字本身
$result[] = array_rand(array_flip($digits)); // 或直接 $digits[array_rand($digits)]
}
echo implode('', $result); // 例:0179571910024734
缺點:迴圈 16 次、陣列操作較慢、首位可能為 0。
random_int() 密碼學級隨機(PHP 7+ 推薦)<?php
// 產生密碼學安全的 16 位數字字串
$bytes = random_bytes(8); // 8 bytes = 64 bits ≈ 19 位十進位,足夠
$rand16 = substr(str_replace(['.', '-'], '', base_convert(bin2hex($bytes), 16, 10)), 0, 16);
// 或更簡單:逐位產生
$result = '';
for ($i = 0; $i < 16; $i++) {
$result .= random_int(0, 9);
}
// 確保首位非 0
if ($result[0] === '0') $result[0] = random_int(1, 9);
echo $result;
適用:需高安全性的 Token、一次性驗證碼。
<?php
/**
* 產生指定長度的隨機字串
* @param int $length 長度
* @param string $charset 字元集
* @param bool $crypto 是否使用密碼學安全隨機源
* @return string
*/
function randomString(int $length = 16, string $charset = '0123456789', bool $crypto = false): string {
$max = strlen($charset) - 1;
$result = '';
for ($i = 0; $i < $length; $i++) {
$idx = $crypto ? random_int(0, $max) : mt_rand(0, $max);
$result .= $charset[$idx];
}
// 避免首字元為 0(純數字時)
if ($charset === '0123456789' && $result[0] === '0') {
$result[0] = $charset[$crypto ? random_int(1, $max) : mt_rand(1, $max)];
}
return $result;
}
// 使用範例
echo randomString(16); // 16 位純數字
echo randomString(32, '0123456789abcdef'); // 32 位十六進位
echo randomString(20, 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789', true); // 安全 Base32
| 方法 | 速度 | 安全性 | 首位非0 | 建議用途 |
|---|---|---|---|---|
| mt_rand 拼接 | ★★★★★ | 低 | 可控 | 一般業務流水號、測試資料 |
| array_rand 迴圈 | ★★☆☆☆ | 低 | 不可控 | 教學示範、非關鍵場景 |
| random_int / random_bytes | ★★★☆☆ | 高 (CSPRNG) | 可控 | Token、驗證碼、加密相關 |
rand():已棄用,品質差、可預測。uniqid():基於微秒時間,並發下極易重複,且非隨機。md5(time()) 截取:熵來源單一,安全性極低。