圖形驗證碼是表單防機器人提交的基本防護。本文提供一組完整的驗證碼產生器(captcha.php)與驗證表單範例,使用 GD 函式庫繪製干擾線與隨機字元。
<?php session_start(); // 設定驗證碼參數 $width = 100; $height = 30; $code_length = 4; $font_size = 5; // 產生隨機字元(0-9, a-f 十六進位) $code = ''; for ($i = 0; $i < $code_length; $i++) { $code .= dechex(rand(1, 15)); } $_SESSION['captcha_code'] = $code; // 建立圖片畫布 $im = imagecreatetruecolor($width, $height); $bg_color = imagecolorallocate($im, 0, 0, 0); // 黑色背景 $text_color = imagecolorallocate($im, 255, 255, 255); // 白色文字 // 填滿背景 imagefilledrectangle($im, 0, 0, $width, $height, $bg_color); // 繪製干擾線(可選) for ($i = 0; $i < 5; $i++) { $line_color = imagecolorallocate($im, rand(100, 200), rand(100, 200), rand(100, 200)); imageline($im, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $line_color); } // 繪製驗證碼文字 $x = 15; $y = 20; imagestring($im, $font_size, $x, $y, $code, $text_color); // 輸出圖片 header('Content-Type: image/jpeg'); imagejpeg($im); imagedestroy($im); ?>
<?php session_start(); $message = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['captcha_input']) && $_POST['captcha_input'] !== '') { if (strtolower($_POST['captcha_input']) === strtolower($_SESSION['captcha_code'] ?? '')) { $message = '<div style="color:green">驗證碼正確!</div>'; // 這裡處理表單業務邏輯 } else { $message = '<div style="color:red">驗證碼錯誤,請重新輸入。</div>'; } } else { $message = '<div style="color:red">請輸入驗證碼。</div>'; } } ?> <!DOCTYPE html> <html> <head><meta charset="utf-8"><title>驗證碼測試</title></head> <body> <h2>驗證碼測試表單</h2> = $message ?> <form method="post"> <img src="captcha.php" alt="驗證碼" style="vertical-align:middle; cursor:pointer" onclick="this.src='captcha.php?'+Date.now()" title="點擊更換"> <br><br> <input type="text" name="captcha_input" placeholder="輸入驗證碼" required> <button type="submit">提交</button> </form> </body> </html>
$_SESSION['captcha_code'],驗證時比對並忽略大小寫。onclick="this.src='captcha.php?'+Date.now()" 讓使用者無需重新整理頁面即可換碼。header('Cache-Control: no-store, no-cache, must-revalidate'); 防止快取,並考慮使用 imagettftext() 載入 TTF 字型提升可讀性與安全性。現代專案建議使用成熟套件如 Gregwar/Captcha 或 mews/captcha(Laravel),支援更多樣化的驗證碼樣式、算術題、中文驗證碼等,且經過社群安全性驗證。