首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 點擊刷新驗證碼完整實現:GD 庫生成、Session 驗證、AJAX 無刷新體驗

     編輯:PHP 相關知識

架構概覽

三文件協作:

  • ValidationCode.class.php —— 核心生成類(GD 繪圖)
  • imgcode.php —— 輸出圖片、寫入 Session
  • demo.php —— 前端頁面、JS 刷新、表單驗證

核心類:ValidationCode

class ValidationCode {
    private $width, $height, $codenum;
    public $checkcode;      // 生成的驗證碼字符串
    private $checkimage;    // GD 圖片資源
    private $disturbColor;  // 干擾像素顏色

    public function __construct($width = 80, $height = 20, $codenum = 4) {
        $this->width = $width;
        $this->height = $height;
        $this->codenum = $codenum;
    }

    public function outImg() {
        $this->outputHeader();
        $this->generateCode();
        $this->createImage();
        $this->setDisturbPixels();
        $this->drawCode();
        imagepng($this->checkimage);
        imagedestroy($this->checkimage);
    }

    private function outputHeader() {
        header('Content-Type: image/png');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Pragma: no-cache');
    }

    private function generateCode() {
        // 取 MD5 前 N 位,大寫,排除易混淆字符可自行擴展
        $this->checkcode = strtoupper(substr(md5(mt_rand()), 0, $this->codenum));
    }

    private function createImage() {
        $this->checkimage = imagecreate($this->width, $this->height);
        $bg = imagecolorallocate($this->checkimage, 255, 255, 255);  // 白底
        $border = imagecolorallocate($this->checkimage, 0, 0, 0);    // 黑框
        imagefilledrectangle($this->checkimage, 0, 0, $this->width-1, $this->height-1, $bg);
        imagerectangle($this->checkimage, 0, 0, $this->width-1, $this->height-1, $border);
    }

    private function setDisturbPixels() {
        for ($i = 0; $i < 200; $i++) {
            $color = imagecolorallocate($this->checkimage, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
            imagesetpixel($this->checkimage, mt_rand(2, $this->width-2), mt_rand(2, $this->height-2), $color);
        }
    }

    private function drawCode() {
        for ($i = 0; $i < $this->codenum; $i++) {
            $color = imagecolorallocate($this->checkimage, mt_rand(0,255), mt_rand(0,128), mt_rand(0,255));
            $x = floor($this->width / $this->codenum) * $i + mt_rand(-2, 2);  // 輕微抖動
            $y = mt_rand(2, $this->height - 15);
            imagechar($this->checkimage, mt_rand(5, 8), $x, $y, $this->checkcode[$i], $color);
        }
    }

    public function __destruct() {
        unset($this->width, $this->height, $this->codenum);
    }
}

圖片輸出端:imgcode.php

session_start();
require_once 'ValidationCode.class.php';

$vc = new ValidationCode(100, 30, 4);  // 寬100、高30、4位
$vc->outImg();
$_SESSION['validation_code'] = $vc->checkcode;  // 大寫存儲

前端頁面:demo.php

session_start();

// 處理提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = strtoupper(trim($_POST['code'] ?? ''));
    if ($input === ($_SESSION['validation_code'] ?? '')) {
        echo '驗證通過!';
    } else {
        echo '驗證碼錯誤';
    }
    exit;
}
?>



    
    點擊刷新驗證碼演示
    


    

登錄驗證

點擊刷新

關鍵細節解析

1. 防緩存機制

imgcode.php?' + Date.now() 確保每次請求 URL 唯一,繞過瀏覽器/代理緩存。後端也發送了 Cache-Control: no-store 雙重保險。

2. 大小寫統一

生成時 strtoupper,驗證時 strtoupper,避免大小寫不敏感導致的用戶困擾。

3. 干擾強度平衡

  • 200 個隨機像素點
  • 字符隨機顏色、字體大小(5-8)、位置抖動
  • 可按需調整:機器識別率 vs 用戶可讀性

4. 安全增強建議

  1. 字符集優化:排除 0/O, 1/I/l, 2/Z, 5/S, 8/B 等易混淆字符
  2. 噪聲曲線:添加 imageline/imagearc 干擾線
  3. 字體文件:用 imagettftext + TTF 字體替代內置字體,效果更佳
  4. 限流:同 IP 分鐘請求上限,防暴力刷新
  5. Session 固定攻擊防護:登錄前 session_regenerate_id(true)

進階:AJAX 無刷新驗證

// JS
$('#loginForm').submit(function(e) {
    e.preventDefault();
    $.post('verify.php', {code: $('#code').val()}, function(res) {
        if (res.ok) location.href = '/dashboard';
        else { alert(res.msg); $('#captcha').click(); }
    }, 'json');
});

// verify.php
session_start();
echo json_encode([
    'ok' => strtoupper($_POST['code']) === ($_SESSION['validation_code'] ?? ''),
    'msg' => '驗證碼錯誤'
]);

總結

基於 GD 庫的驗證碼生成是 PHP 經典技能。本實現涵蓋圖片生成、Session 綁定、前端點擊刷新、表單驗證完整鏈路。生產環境建議結合字符集優化、TTF 字體、干擾曲線、請求限流等措施,並在關鍵業務(登錄、註冊、支付)部署。現代項目亦可考慮 Google reCAPTCHA v3 / hCaptcha / 行為驗證 等零交互方案提升用戶體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved