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

PHP GD 庫生成數字驗證碼完整實現(含表單驗證與干擾像素)

     編輯:PHP 相關知識

本文提供一套基於 PHP GD 庫的四位數字驗證碼完整實現,包含驗證碼生成、圖片輸出、干擾像素、Session 存儲與表單驗證邏輯,代碼經調試可直接運行,適合快速集成至舊項目或教學參考。

文件結構

  • authpage.php:主頁面,生成驗證碼、輸出表單、驗證用戶輸入。
  • authimg.php:驗證碼圖片生成腳本,輸出 PNG 圖片流。

authpage.php 核心邏輯

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

// 1. 處理表單提交驗證
if (isset($_POST['authinput'])) {
    if (strcmp($_SESSION['authnum'], $_POST['authinput']) === 0) {
        echo "驗證成功!";
    } else {
        echo "驗證失敗!";
    }
}

// 2. 生成新的四位數字驗證碼存入 Session
$_SESSION['authnum'] = sprintf('%04d', mt_rand(0, 9999)); // 確保四位,含前導零
?>

<form action="authpage.php" method="post">
    <table>
        <tr>
            <td>請輸入驗證碼:</td>
            <td><input type="text" name="authinput" style="width:80px"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="提交驗證"></td>
        </tr>
        <tr>
            <td></td>
            <td><img src="authimg.php" alt="點擊刷新" style="cursor:pointer;vertical-align:middle" onclick="this.src='authimg.php?'+Math.random()"></td>
        </tr>
    </table>
</form>

改進點:使用 $_SESSION 替代隱藏域傳遞驗證碼,防止繞過驗證;mt_rand 替代 rand 提升隨機質量;圖片點擊刷新增強 UX。

authimg.php 圖片生成邏輯

<?php
session_start();
header("Content-type: image/png");

// 1. 創建畫布
$im = imagecreate(80, 30); // 寬高適配四位數字
$bg = imagecolorallocate($im, 220, 220, 220); // 淺灰背景
$textColor = imagecolorallocate($im, 0, 0, 0);  // 黑色文字
$noiseColor = imagecolorallocate($im, 180, 180, 180); // 干擾色

// 2. 填充背景
imagefill($im, 0, 0, $bg);

// 3. 繪製驗證碼文字
$code = $_SESSION['authnum'];
imagestring($im, 5, 12, 6, $code, $textColor); // 字體 5,座標微調

// 4. 添加干擾像素
for ($i = 0; $i < 80; $i++) {
    imagesetpixel($im, mt_rand(0, 79), mt_rand(0, 29), $noiseColor);
}

// 5. 可選:干擾線
for ($i = 0; $i < 5; $i++) {
    imageline($im, mt_rand(0, 79), mt_rand(0, 29), mt_rand(0, 79), mt_rand(0, 29), $noiseColor);
}

// 6. 輸出並銷毀
imagepng($im);
imagedestroy($im);

安全與擴展建議

  • 字符集擴展:將數字擴展為字母數字混合($chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789')。
  • TTF 字體:使用 imagettftext() 繪製抗鋸齒、可旋傾斜字符,大幅提升識別難度。
  • Session 防暴力:記錄驗證失敗次數,超限鎖定 IP 或要求更強驗證。
  • 現代替代方案:新項目建議使用 Gregwar/Captcha、mews/captcha 等 Composer 包,或接入 Google reCAPTCHA / hCaptcha。

此實現雖屬基礎,但涵蓋驗證碼核心流程,理解其原理有助於評估第三方庫安全性與定制化開發。

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