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

PHP 數字驗證碼實現全流程:GD 庫 + Session 實戰

     編輯:PHP 相關知識

原理概述

驗證碼核心:GD 庫生成干擾圖片 + Session 存儲驗證值 + 表單提交比對。本例演示 4 位純數字驗證碼。

文件結構

  • authpage.php:主頁,顯示表單與驗證碼圖片,處理提交驗證。
  • authimg.php:動態生成驗證碼圖片並寫入 Session。

authpage.php 完整代碼

<?php
session_start();
$authnum = $_SESSION['authnum'] ?? '';

if (isset($_POST['authinput'])) {
    if (strcmp($_POST['authinput'], $_SESSION['authnum']) === 0) {
        echo "驗證成功!";
    } else {
        echo "驗證失敗!";
    }
}
?>
<form action="authpage.php" method="post">
<table>
<tr><td>請輸入驗證碼:<input type="text" name="authinput"></td></tr>
<tr><td><input type="submit" name="驗證" value="提交驗證碼"></td></tr>
<tr><td><img src="authimg.php" alt="驗證碼"></td></tr>
</table>
</form>

authimg.php 完整代碼

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

$im = imagecreate(62, 20);               // 創建畫布
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
$gray  = imagecolorallocate($im, 200, 200, 200);

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

// 生成 4 位隨機數
srand((double)microtime() * 1000000);
while (($authnum = rand() % 10000) < 1000); // 確保 4 位
$_SESSION['authnum'] = $authnum;

// 繪製數字
imagestring($im, 5, 10, 3, $authnum, $black);

// 添加干擾像素
for ($i = 0; $i < 200; $i++) {
    $randcolor = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
    imagesetpixel($im, rand()%70, rand()%30, $randcolor);
}

imagepng($im);
imagedestroy($im);
?>

關鍵點詳解

  1. Session 同步:兩文件均需 session_start(),確保同一會話。
  2. 隨機種子:srand((double)microtime()*1000000) 增加熵(PHP 4.2+ 可省略)。
  3. 干擾像素:200 個隨機色像素有效對抗 OCR 識別。
  4. 輸出頭:header("Content-type: image/PNG") 告知瀏覽器圖片類型。

擴展方向

  • 字母數字混合、中文驗證碼(需字體文件)。
  • 增加干擾線、扭曲、噪點提高安全性。
  • 使用 imagefttext 支持 TrueType 字體渲染更美觀。

總結

數字驗證碼是 PHP GD 庫入門最佳實踐,掌握畫布創建、顏色分配、字符串繪製、像素操作、Session 交互五大核心技能,即可靈活構建各類驗證碼系統。

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