萬盛學電腦網

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

PHP 入門級驗證碼程式實作:GD 庫生成圖形驗證碼完整教學(含干擾線、噪點、TTF 字體)

核心原理

利用 GD 擴展建立畫布 → 分配顏色 → 繪製背景/干擾線/點 → 繪製隨機字元 → 輸出 PNG 二進制流 → 存入 Session 驗證。

版本一:基礎版(imagechar 固定字體)

<?php
session_start();

$width = 80;
$height = 30;
$im = imagecreate($width, $height);           // 建立調色盤圖片

// 隨機背景色(淡色系)
$bg_color = imagecolorallocate($im, rand(150,200), rand(150,200), rand(150,200));

// 字元池
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';
$code = '';
for ($i = 0; $i < 5; $i++) {
    $code .= $chars[rand(0, strlen($chars) - 1)];
}
$_SESSION['code'] = $code;  // 存入 Session 驗證

// 繪製字元(黑色)
$text_color = imagecolorallocate($im, 0, 0, 0);
for ($i = 0; $i < 5; $i++) {
    $x = $i * 10 + 15;
    $y = rand(5, 10);
    imagechar($im, 5, $x, $y, $code[$i], $text_color);
}

header("Content-Type: image/png");
imagepng($im);
imagedestroy($im);
?>

版本二:進階版(TTF 字體 + 干擾線 + 噪點 + 旋轉)

<?php
if (!isset($_SESSION)) session_start();

$width  = 70;
$height = 25;
$length = 4;

$code = getCode($length);
$_SESSION['verfyCode'] = $code;

$img = imagecreate($width, $height);

// 背景色
$bg_color = imagecolorallocate($img, 240, 240, 240);
// 邊框色
$border_color = imagecolorallocate($img, 150, 150, 150);
imagerectangle($img, 1, 1, $width-1, $height-1, $border_color);

// 繪製字元(TTF 字體、隨機顏色、隨機角度)
for ($i = 0; $i < $length; $i++) {
    $text_color = imagecolorallocate($img, mt_rand(50,200), mt_rand(50,128), mt_rand(50,200));
    $angle = rand(-20, 20);
    $x = $i * 15 + 8;
    $y = ($height + 14) / 2 + rand(-1, 1);
    // 注意:字體路徑需根據實際環境調整
    imagettftext($img, 15, $angle, $x, $y, $text_color, 'C:/Windows/Fonts/SIMKAI.TTF', $code[$i]);
}

// 干擾線
for ($i = 0; $i < 20; $i++) {
    $line_color = imagecolorallocate($img, mt_rand(0,250), mt_rand(0,250), mt_rand(0,250));
    $x1 = mt_rand(1, $width-1);
    $y1 = mt_rand(1, $height-1);
    $x2 = $x1 + mt_rand(0,4) - 2;
    $y2 = $y1 + mt_rand(0,4) - 2;
    imageline($img, $x1, $y1, $x2, $y2, $line_color);
}

// 噪點
for ($i = 0; $i < 100; $i++) {
    $point_color = imagecolorallocate($img, mt_rand(0,250), mt_rand(0,250), mt_rand(0,250));
    imagesetpixel($img, mt_rand(1,$width-1), mt_rand(1,$height-1), $point_color);
}

function getCode($length) {
    $pattern = '1234567890ABCDEFGHIJKLOMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $key = '';
    for ($i = 0; $i < $length; $i++) {
        $key .= $pattern[mt_rand(0, strlen($pattern)-1)];
    }
    return $key;
}

ob_clean();  // 清除前序輸出
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
?>

關鍵函數速查表

函數用途
imagecreate(w,h)建立調色盤圖片資源
imagecreatetruecolor(w,h)建立真彩色圖片(支援透明度、更多顏色)
imagecolorallocate($im, r,g,b)分配顏色 ID
imagechar($im, font, x, y, char, color)繪製單一字元(內建 1-5 號字體)
imagettftext($im, size, angle, x, y, color, fontfile, text)繪製 TTF 字體文字(需 FreeType 支援)
imageline($im, x1,y1, x2,y2, color)繪製直線
imagesetpixel($im, x, y, color)繪製單一像素
imagepng($im)輸出 PNG 格式
imagedestroy($im)釋放記憶體

常見問題與解決

  1. 字體路徑錯誤:Windows 絕對路徑 C:/Windows/Fonts/xxx.ttf,Linux 常見 /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf,建議專案內放置字體檔相對路徑引用。
  2. 中文亂碼:確保 PHP 檔案編碼為 UTF-8,字體支援中文字符,imagettftext 直接傳入 UTF-8 字串即可。
  3. Session 驗證失敗:確認 session_start() 在所有輸出前調用,檢查 session.save_path 可寫入。
  4. 輸出前有空白/換行:使用 ob_clean() 或確保 <?php 為檔案第一字元、結尾無 ?>。

安全性增強建議

  • 🔐 使用 random_int() 替代 rand()/mt_rand()(密碼學安全)
  • 🎨 採用 imagecreatetruecolor() + Alpha 混合實現半透明干擾
  • 🔤 字元池排除易混淆字元(0/O, 1/l/I, 8/B 等)
  • ⏱️ 加入驗證碼有效期(如 5 分鐘),驗證後立即 unset($_SESSION['code']) 防重放
  • 🛡️ 結合限流、IP 封鎖、行為分析防暴力破解
  • 效果展示

    驗證碼效果圖

    總結

    GD 庫生成驗證碼是 PHP 經典入門實作。從基礎 imagechar 到進階 imagettftext + 干擾元素,核心在於:隨機性、可讀性與機器識別難度的平衡。實務專案建議直接採用成熟套件(如 gregwar/captcha、mewebstudio/captcha),或升級至無感驗證(reCAPTCHA v3、Turnstile)提升用戶體驗。

copyright © 萬盛學電腦網 all rights reserved