產生隨機字串是驗證碼、API Token、臨時密碼、訂單編號等常見需求。本文提供可調整長度、字元集的通用函式,並比較安全性差異。
基本實作
<?php
/**
* 產生隨機字母數字字串
* @param int $length 長度 (預設 8)
* @param string $charset 字元集 (預設大小寫字母+數字)
* @return string
*/
function generateRandomString(int $length = 8, string $charset = ''): string {
$charset = $charset ?: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$max = strlen($charset) - 1;
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $charset[random_int(0, $max)];
}
return $result;
}
// 使用範例
echo generateRandomString(6) . "\n"; // 如: aB3fG9
echo generateRandomString(10, '0123456789') . "\n"; // 純數字 10 碼
echo generateRandomString(32, '0123456789abcdef') . "\n"; // 32 字元十六進位
?>
原始碼版本 (使用 rand/str_pad)
<?php
// 原始碼風格 (不推薦:rand() 非加密安全、str_pad 用法怪異)
function makecode($num = 4) {
$re = '';
$s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
while (strlen($re) < $num) {
$re .= $s[rand(0, strlen($s) - 1)];
}
return $re;
}
?>
安全性關鍵:random_int vs rand/mt_rand
| 函式 | 隨機來源 | 加密安全 | 用途 |
| random_int() | OS CSPRNG (/dev/urandom, CryptGenRandom) | ✅ 是 | Token、密碼、Session ID、加密金鑰 |
| mt_rand() | Mersenne Twister (PHP 7.1+) | ❌ 否 | 遊戲、模擬、非安全隨機 |
| rand() | 同 mt_rand (PHP 7.1+) | ❌ 否 | 不建議使用 |
| shuffle() | 同上 | ❌ 否 | 陣列打亂 |
專用場景最佳實務
1. CSRF Token / API Token
<?php
function generateToken(int $bytes = 32): string {
return bin2hex(random_bytes($bytes)); // 64 字元十六進位
}
// 或
function generateTokenB64(int $bytes = 32): string {
return rtrim(strtr(base64_encode(random_bytes($bytes)), '+/', '-_'), '='); // URL-safe Base64
}
?>
2. 使用者可讀的隨機代碼 (排除易混淆字元)
<?php
function generateHumanCode(int $length = 8): string {
$charset = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; // 移除 0,1,I,O,U 等易混字元
return generateRandomString($length, $charset);
}
?>
3. 密碼產生 (含符號)
<?php
function generatePassword(int $length = 16): string {
$charset = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%^&*';
return generateRandomString($length, $charset);
}
?>
4. UUID v4 (標準格式)
<?php
function generateUuidV4(): string {
$bytes = random_bytes(16);
// 設定版本 (4) 和變體 (10x)
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}
?>
效能優化:批次生成
<?php
function generateBatch(int $count, int $length = 8): array {
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$max = strlen($charset) - 1;
$results = [];
for ($i = 0; $i < $count; $i++) {
$bytes = random_bytes($length);
$result = '';
for ($j = 0; $j < $length; $j++) {
$result .= $charset[$bytes[$j] % ($max + 1)];
}
$results[] = $result;
}
return $results;
}
// 生成 1000 組 16 字元 Token
$tokens = generateBatch(1000, 16);
?>
copyright ©
萬盛學電腦網 all rights reserved