在實際開發中,常需要產生指定長度的隨機字串,用於 API Token、驗證碼、臨時檔名等場景。本文提供一個簡單易用的 random() 函數,支援自訂長度與字元集。
<?php
/**
* 產生指定長度的隨機字串
*
* @param int $length 字串長度
* @param string $chars 可用字元集 (預設: 大寫字母+數字)
* @return string 隨機字串
*/
function random($length, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
// PHP 7.0+ 建議使用 random_int() 取代 rand()
$maxIndex = strlen($chars) - 1;
$result = '';
for ($i = 0; $i < $length; $i++) {
// 使用隨機索引選取字元
$randomIndex = random_int(0, $maxIndex);
$result .= $chars[$randomIndex];
}
return $result;
}
// 使用範例
echo random(8); // 輸出如: K7B2X9A1
echo random(16, 'abcdef0123456789'); // 十六進位字串
?>
若需包含小寫字母、特殊符號,可擴充字元集:
<?php
function randomString($length, $type = 'alnum')
{
$pools = [
'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'alnum' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'numeric' => '0123456789',
'hex' => '0123456789abcdef',
'safe' => '23456789ABCDEFGHJKLMNPQRSTUVWXYZ', // 移除易混淆字元
'all' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()',
];
$chars = $pools[$type] ?? $pools['alnum'];
$maxIndex = strlen($chars) - 1;
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $chars[random_int(0, $maxIndex)];
}
return $result;
}
// 使用範例
echo randomString(10, 'safe'); // 適合人工輸入的驗證碼
echo randomString(32, 'hex'); // 32 字元十六進位 (如 MD5 長度)
?>
rand() 並非密碼學安全。PHP 7.0+ 請改用 random_int() 或 random_bytes()。srand(date('s')) 種子空間極小(僅 0-59),極易被暴力破解,切勿用於安全敏感場景。uniqid()、UUID 或資料庫自增 ID。PHP 8.2+ 可直接使用 Random\Randomizer 類別:
<?php
$randomizer = new Random\Randomizer();
$bytes = $randomizer->getBytes(16); // 16 位元組二進位資料
$hex = bin2hex($bytes); // 轉為 32 字元十六進位字串
?>