萬盛學電腦網

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

PHP GD 庫打造動態驗證碼:從基礎繪圖到完整封裝

什麼是 CAPTCHA?

CAPTCHA(全自動區分計算機和人類的圖靈測試)廣泛用於防止暴力破解、刷票、垃圾留言。本文將帶您從零開始,使用 PHP GD 庫構建一個支援干擾線、噪點、隨機字符的動態驗證碼,並封裝為可複用函數。

GD 繪圖基礎流程

  1. 設置 Header:header('Content-Type: image/png');
  2. 創建畫布:$im = imagecreatetruecolor(200, 200);
  3. 分配顏色並填充背景:$blue = imagecolorallocate($im, 0, 102, 255); imagefill($im, 0, 0, $blue);
  4. 繪製干擾元素(線條、文字)
  5. 輸出圖片:imagepng($im);
  6. 銷毀資源:imagedestroy($im);

完整驗證碼封裝函數 _code()

/**
 * 驗證碼生成函數
 * @param int  $_width   畫布寬度(建議:6 位約 125px,8 位約 175px)
 * @param int  $_height  畫布高度(建議 30-50px)
 * @param int  $_rnd_code 驗證碼位數
 * @param bool $_flag    是否顯示邊框
 */
function _code($_width = 125, $_height = 35, $_rnd_code = 6, $_flag = false) {
    session_start();

    // 1. 生成隨機字符(十六進制)
    $_nmsg = '';
    for ($i = 0; $i < $_rnd_code; $i++) {
        $_nmsg .= dechex(mt_rand(0, 15));
    }
    $_SESSION['code'] = $_nmsg; // 存入 Session 驗證

    // 2. 創建畫布
    $_img = imagecreatetruecolor($_width, $_height);
    $_white = imagecolorallocate($_img, 255, 255, 255);
    imagefill($_img, 0, 0, $_white);

    // 3. 邊框
    if ($_flag) {
        $_black = imagecolorallocate($_img, 0, 0, 0);
        imagerectangle($_img, 0, 0, $_width - 1, $_height - 1, $_black);
    }

    // 4. 干擾線
    for ($i = 0; $i < 6; $i++) {
        $_rnd_color = imagecolorallocate($_img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
        imageline($_img, mt_rand(0, $_width), mt_rand(0, $_height), mt_rand(0, $_width), mt_rand(0, $_height), $_rnd_color);
    }

    // 5. 噪點(雪花)
    for ($i = 0; $i < 100; $i++) {
        $_rnd_color = imagecolorallocate($_img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
        imagestring($_img, 1, mt_rand(1, $_width), mt_rand(1, $_height), '*', $_rnd_color);
    }

    // 6. 繪製驗證碼字符
    for ($i = 0; $i < strlen($_SESSION['code']); $i++) {
        $_rnd_color = imagecolorallocate($_img, mt_rand(0, 100), mt_rand(0, 150), mt_rand(0, 200));
        // 隨機位置增加識別難度
        $x = $i * $_width / $_rnd_code + mt_rand(1, 10);
        $y = mt_rand(1, $_height / 2);
        imagestring($_img, 5, $x, $y, $_SESSION['code'][$i], $_rnd_color);
    }

    // 7. 輸出與清理
    header('Content-Type: image/png');
    imagepng($_img);
    imagedestroy($_img);
}

前端調用方式

<img src="captcha.php" alt="驗證碼" onclick="this.src='captcha.php?'+Math.random()" />

點擊圖片即可刷新,captcha.php 中只需 require 'global.func.php'; _code(); 即可。

安全性增強建議

  • 使用 TTF 字體 imagettftext() 替換內建字體,增加變形與旋轉
  • 加入扭曲、波浪等幾何變換
  • 驗證時區分大小寫或統一轉大小寫比對
  • 限制驗證碼使用次數與有效期(如 5 分鐘)
copyright © 萬盛學電腦網 all rights reserved