萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 圖形驗證碼完整實作:GD 庫生成、Session 驗證、干擾像素

架構設計

兩檔案分離:

  • authpage.php:主頁面、表單、驗證邏輯、顯示驗證碼圖片
  • authimg.php:專責生成驗證碼圖片

authpage.php - 主程式

<?php
session_start();  // 必須啟用 Session

// 1. 處理表單提交驗證
if (isset($_POST['authinput'])) {
    // 從 Session 取得正確驗證碼(比隱藏欄位安全)
    $correctCode = isset($_SESSION['auth_code']) ? $_SESSION['auth_code'] : '';
    $userInput = trim($_POST['authinput']);
    
    if (strcasecmp($correctCode, $userInput) === 0) {
        echo "
驗證成功!
"; } else { echo "
驗證失敗!
"; } } // 2. 產生新驗證碼(4 位數字) $authCode = sprintf('%04d', mt_rand(0, 9999)); $_SESSION['auth_code'] = $authCode; // 存入 Session ?> <!DOCTYPE html> <html> <head><title>驗證碼測試</title></head> <body> <form action="authpage.php" method="post"> <table> <tr> <td>請輸入驗證碼:</td> <td><input type="text" name="authinput" maxlength="4" style="width:80px; text-align:center;" /></td> </tr> <tr> <td></td> <td> <input type="submit" value="提交驗證" /> <img src="authimg.php?t=" alt="驗證碼" style="vertical-align:middle; cursor:pointer;" title="點擊更換" onclick="this.src='authimg.php?t='+Date.now()" /> </td> </tr> </table> </form> </body> </html>

authimg.php - 圖片生成器

<?php
session_start();

// 設定圖片標頭
header("Content-Type: image/png");
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

// 畫布設定
$width = 80;
$height = 30;
$im = imagecreatetruecolor($width, $height);  // TrueColor 支援更多顏色

// 顏色分配
$bgColor = imagecolorallocate($im, 220, 220, 220);  // 淺灰背景
$textColor = imagecolorallocate($im, 0, 0, 0);      // 黑字
$noiseColor = imagecolorallocate($im, 180, 180, 180); // 干擾色

// 填充背景
imagefill($im, 0, 0, $bgColor);

// 從 Session 取得驗證碼
$authCode = isset($_SESSION['auth_code']) ? $_SESSION['auth_code'] : '0000';

// 繪製文字(置中)
$fontSize = 5;  // 內建字體 1-5
$charWidth = imagefontwidth($fontSize);
$charHeight = imagefontheight($fontSize);
$x = ($width - $charWidth * 4) / 2;
$y = ($height - $charHeight) / 2;
imagestring($im, $fontSize, $x, $y, $authCode, $textColor);

// 加入干擾像素
for ($i = 0; $i < 50; $i++) {
    imagesetpixel($im, mt_rand(0, $width-1), mt_rand(0, $height-1), $noiseColor);
}

// 可選:干擾線
for ($i = 0; $i < 3; $i++) {
    imageline($im, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $noiseColor);
}

// 輸出並銷毀
imagepng($im);
imagedestroy($im);
?>

關鍵安全強化

原版問題改進方案
驗證碼放在 hidden input前端可竄改 → 存入 Session
srand((double)microtime()*1000000)PHP 4.2+ 自動播種,改用 mt_rand()
imagecreate() 調色盤模式imagecreatetruecolor() TrueColor
無快取控制加入 Cache-Control: no-cache
無重新整理機制圖片加 onclick 更新 src + 時間戳
大小寫敏感比對strcasecmp() 不分大小寫

進階擴充:字母數字混合、中文、TTF 字體

// 字元池
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';  // 排除易混淆字元
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= $chars[mt_rand(0, strlen($chars)-1)];
}
$_SESSION['auth_code'] = $code;

// 使用 TTF 字體(需 FreeType 支援)
$fontFile = '/path/to/font.ttf';
imagettftext($im, 18, 0, 15, 22, $textColor, $fontFile, $code);

現代替代方案

  • Google reCAPTCHA v3:無感驗證、機器學習判斷機器人
  • hCaptcha:隱私優先、支援中文
  • Turnstile (Cloudflare):免費、無 Cookie
  • 滑動拼圖/點選文字:體驗更好、安全性高
copyright © 萬盛學電腦網 all rights reserved