圖形驗證碼是防止機器人惡意提交表單的經典手段。本文提供一套完整、可直接部署的範例,涵蓋前端頁面(HTML + JS 重新整理)、驗證碼圖片產生器(verifycode.php)、後端驗證邏輯(checkcode.php),並說明關鍵細節與安全強化建議。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>驗證碼示範</title>
<script>
function refreshCode() {
// 加入隨機參數避免瀏覽器快取舊圖片
document.getElementById('imgcode').src = 'verifycode.php?' + Math.random();
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="checkcode.php">
<label for="code">驗證碼:</label>
<input type="text" name="code" id="code" required>
<img id="imgcode" src="verifycode.php" alt="驗證碼" style="vertical-align:middle; cursor:pointer;" onclick="refreshCode()">
<a href="javascript:refreshCode()">看不清?換一張</a>
<input type="submit" value="提交">
</form>
</body>
</html>
<?php
session_start();
// 參數設定
$num = 4; // 驗證碼字元數
$width = 100; // 圖片寬度
$height = 30; // 圖片高度
$code = '';
// 1. 產生隨機字元(數字 + 大小寫英文)
for ($i = 0; $i < $num; $i++) {
$type = rand(0, 2);
switch ($type) {
case 0: $code[$i] = chr(rand(48, 57)); break; // 0-9
case 1: $code[$i] = chr(rand(65, 90)); break; // A-Z
case 2: $code[$i] = chr(rand(97, 122)); break; // a-z
}
}
$codeStr = implode('', $code);
// 2. 存入 Session(大小寫不敏感比對時統一轉大寫)
$_SESSION['VerifyCode'] = strtoupper($codeStr);
// 3. 建立圖片資源
$image = imagecreatetruecolor($width, $height); // 真彩色支援透明度
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white); // 填滿白底
// 4. 繪製干擾像素(噪點)
for ($i = 0; $i < 60; $i++) {
$noiseColor = imagecolorallocate($image, rand(150, 255), rand(150, 255), rand(150, 255));
imagesetpixel($image, rand(1, $width), rand(1, $height), $noiseColor);
}
// 5. 繪製干擾線條
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}
// 6. 繪製驗證碼字元
for ($i = 0; $i < $num; $i++) {
$charColor = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
$x = ($width / $num) * $i + rand(2, 5);
$y = rand(2, $height - 15);
// 使用 imagettftext 需要 TTF 字型檔,這裡示範內建字型
imagestring($image, 5, $x, $y, $code[$i], $charColor);
}
// 7. 輸出圖片
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
<?php
session_start();
// 取得使用者輸入並轉大寫
$userCode = isset($_POST['code']) ? strtoupper(trim($_POST['code'])) : '';
$validCode = isset($_SESSION['VerifyCode']) ? $_SESSION['VerifyCode'] : '';
// 驗證
if ($userCode === $validCode && $userCode !== '') {
echo '驗證碼正確 ✅';
// 這裡可執行實際業務邏輯(如登入、發表留言)
} else {
echo '驗證碼錯誤 ❌';
}
// 除錯用:顯示對照值(正式環境請移除)
// echo "<br>輸入: $userCode, 正確: $validCode";
?>
session_start() 必須在任何輸出前呼叫,且兩支 PHP 都需呼叫。strtoupper(),提升使用者體驗。unset($_SESSION['VerifyCode']),避免同一張圖被重複使用。這套「前端頁面 → 圖片產生器 → 後端驗證」的三檔案架構清晰、易於整合。理解 GD 函式庫繪圖流程(建立畫布 → 分配顏色 → 繪製形狀/文字 → 輸出)是客製化驗證碼的基礎。實務上建議直接採用成熟的 Composer 套件(如 gregwar/captcha)或第三方服務,減少維護成本並獲得更強防護。