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

PHP 圖形驗證碼完整實作:英數混合與中文版本

     編輯:PHP 綜合知識

PHP GD 庫生成驗證碼完整指南

驗證碼是防止機器人惡意提交表單的基礎防線。本文提供兩個完整實作:英數混合版與中文字符版,涵蓋 Session 驗證、干擾線/像素、字體渲染等核心技術。

版本一:英數混合驗證碼

特點:輕量、相容性高、無需外部字體檔案

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

$chars = 'abcdefghijkmnpqrstuvwxyz23456789'; // 排除易混淆字符
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= $chars[mt_rand(0, strlen($chars) - 1)];
}
$_SESSION['captcha_code'] = $code;

// 建立畫布
$im = imagecreate(80, 30);
$bg = imagecolorallocate($im, 230, 230, 230);
$text_color = imagecolorallocate($im, 0, 0, 0);
$noise_color = imagecolorallocate($im, 180, 180, 180);

// 干擾像素
for ($i = 0; $i < 100; $i++) {
    imagesetpixel($im, mt_rand(0, 80), mt_rand(0, 30), $noise_color);
}
// 干擾線
for ($i = 0; $i < 3; $i++) {
    imageline($im, mt_rand(0, 80), mt_rand(0, 30), mt_rand(0, 80), mt_rand(0, 30), $noise_color);
}

// 繪製文字
imagestring($im, 5, 10, 5, $code, $text_color);

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

版本二:中文驗證碼(TrueType 字體)

特點:辨識難度高、需 TTF 字體檔、支援中文字符

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

$chinese_chars = ["人","出","來","友","學","孝","仁","義","禮","廉","忠","國","中","易","白","者","火","土","金","木","雷","風","龍","虎","天","地","生","暈","菜","鳥","田","三","百","錢","福","愛","情","獸","蟲","魚","九","網","新","度","哎","唉","啊","哦","儀","老","少","日","月","星"];

$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= $chinese_chars[array_rand($chinese_chars)];
}
$_SESSION['captcha_code'] = $code;

// TrueColor 畫布
$im = imagecreatetruecolor(130, 40);
$bg = imagecolorallocate($im, 20, 20, 20);
$text_color = imagecolorallocate($im, 255, 255, 255);

// 需準備 gbk.ttf 或其他中文字體檔
$font = __DIR__ . '/fonts/gbk.ttf';
imagettftext($im, 20, 0, 15, 28, $text_color, $font, $code);

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

前端驗證整合

<!-- HTML 表單 -->
<img src="captcha.php" id="captchaImg" onclick="this.src='captcha.php?'+Math.random()" style="cursor:pointer" />
<input type="text" name="captcha_input" required />

<!-- PHP 驗證 -->
<?php
session_start();
if (strtolower($_POST['captcha_input']) !== strtolower($_SESSION['captcha_code'])) {
    die('驗證碼錯誤');
}
// 通過驗證,處理業務邏輯
?>

安全性增強建議

  • 使用 mt_rand() 或 random_int() 替代 rand()
  • 增加字符旋轉、扭曲、顏色隨機化
  • 限制驗證碼有效期(如 10 分鐘)
  • 驗證後立即銷毀 Session 防重放攻擊
  • 考慮引入 Google reCAPTCHA v3 或 hCaptcha 作為更現代的替代方案
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved