驗證碼是防止機器人惡意提交表單的關鍵機制。本文完整示範 PHP 驗證碼的三階段實作:前端顯示頁面、後端圖片產生、驗證邏輯處理,並說明 Session 同步與 GD 函式庫需求。
index.php頁面包含:驗證碼圖片(透過 <iframe> 或 <img> 載入)、重新整理按鈕、輸入框與提交表單。
<?php
session_start();
header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP 驗證碼示例</title>
</head>
<body>
<p>驗證碼:<br>
<iframe id="iimg" src="img.php" width="300" height="100" frameborder="0"></iframe><br>
<input type="button" value="看不清,換一張" onclick="iimg.location.reload();"><br>
<form action="validate.php" method="post">
輸入驗證碼:<input name="imgId" style="width:60px">
<input type="submit" value="確定">
</form>
</body>
</html>
img.php核心步驟:啟動 Session、產生隨機字串、寫入 Session、使用 GD 繪製干擾線與文字、輸出 GIF 圖片、銷毀圖片資源。
<?php
session_start();
header('Content-Type: image/gif');
// 產生 6 位隨機字元(大寫字母+數字)
$randval = '';
for ($i = 0; $i < 6; $i++) {
$type = mt_rand(0, 1);
$randval .= ($type === 0) ? chr(mt_rand(ord('A'), ord('Z'))) : mt_rand(0, 9);
}
// 存入 Session(注意:session_register 已棄用,直接賦值 $_SESSION)
$_SESSION['captcha_code'] = $randval;
// 建立真彩色圖片
$width = 120; $height = 40;
$im = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($im, 255, 255, 255);
$blue = imagecolorallocate($im, 0, 0, 128);
imagefill($im, 0, 0, $white);
// 繪製干擾線
for ($k = 0; $k < 5; $k++) {
imageline($im, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $blue);
}
// 繪製驗證碼文字
imagestring($im, 5, mt_rand(5, $width - 60), mt_rand(5, $height - 20), $randval, $blue);
imagegif($im);
imagedestroy($im);
?>
注意:需啟用 PHP GD 擴充套件(extension=gd),且儲存檔案為無 BOM UTF-8 編碼。
validate.php取得使用者輸入、轉大寫、與 Session 比對、銷毀 Session 防重複使用。
<?php
session_start();
header('Content-Type: text/html; charset=UTF-8');
$input = isset($_POST['imgId']) ? strtoupper(trim($_POST['imgId'])) : '';
$code = isset($_SESSION['captcha_code']) ? $_SESSION['captcha_code'] : '';
if ($input !== '' && $input === $code) {
echo '<font color="blue">通過驗證!</font>';
} else {
echo '<font color="red">驗證錯誤!</font>';
}
// 驗證後銷毀,防止重放攻擊
session_destroy();
?>
imagettftext() 產生更難辨識的扭曲文字。imagesetpixel()、imageellipse() 提高機器辨識難度。$_SESSION['captcha']['login']。透過 Session 同步隨機字串與 GD 繪圖,即可快速建立可用的驗證碼機制。實務專案建議採用成熟套件並結合前端 AJAX 驗證,提升使用者體驗與安全性。