表單驗證碼常需字母數字混合以提高安全性。本文提供一個通用函數,可指定長度生成包含大小寫字母與數字的隨機字串,核心採用 mt_rand() 確保效能與隨機品質。
<?php
/**
* 生成指定長度的字母數字混合隨機字串
* @param int $length 字串長度,預設 4
* @return string 隨機字串
*/
function generateRandomString($length = 4) {
$chars = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
$maxIndex = count($chars) - 1;
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $chars[mt_rand(0, $maxIndex)];
}
return $result;
}
// 使用範例
echo generateRandomString(4); // 如: a7K9
echo generateRandomString(6); // 如: Xy3mP9
?>
rand() 快 4 倍,隨機品質更好。語法:mt_rand(min, max) 返回 [min, max] 間整數。實際專案中通常需生成圖片驗證碼(CAPTCHA),建議使用 GD 或 ImageMagick:
<?php
session_start();
$code = generateRandomString(4);
$_SESSION['captcha'] = strtoupper($code); // 不區分大小寫驗證
$img = imagecreatetruecolor(100, 40);
$bg = imagecolorallocate($img, 240, 240, 240);
$textColor = imagecolorallocate($img, 50, 50, 50);
imagefill($img, 0, 0, $bg);
// 加入干擾線、噪點...
imagettftext($img, 20, 0, 15, 30, $textColor, 'arial.ttf', $code);
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
?>