萬盛學電腦網

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

PHP GD 库生成验证码图片:数字/字母/中文、干扰点线、Session 存储、TTF 字体支持完整实现

验证码核心流程

  1. 创建画布 imagecreatetruecolor()
  2. 分配背景色、文字色、干扰色
  3. 填充背景、绘制干扰点/线
  4. 生成随机字符,绘制到画布
  5. 存入 Session 供后续验证
  6. 输出 HTTP 头 + 图片二进制
  7. 销毁画布释放内存

版本一:经典数字字母验证码(内置字体)

<?php
session_start();

$width = 100; $height = 30;
$img = imagecreatetruecolor($width, $height);

// 背景白
$bg = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $bg);

// 4 位随机数字
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= mt_rand(0, 9);
    $color = imagecolorallocate($img, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
    $x = $i * $width / 4 + mt_rand(5, 15);
    $y = mt_rand(5, 15);
    imagestring($img, 5, $x, $y, $code[$i], $color); // 内置字体 5
}

$_SESSION['captcha'] = $code;

// 干扰点
for ($i = 0; $i < 200; $i++) {
    $color = imagecolorallocate($img, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
    imagesetpixel($img, mt_rand(1, $width-1), mt_rand(1, $height-1), $color);
}

// 干扰线
for ($i = 0; $i < 3; $i++) {
    $color = imagecolorallocate($img, mt_rand(100, 250), mt_rand(100, 250), mt_rand(100, 250));
    imageline($img, mt_rand(0, $width/2), mt_rand(0, $height/2), mt_rand($width/2, $width), mt_rand($height/2, $height), $color);
}

header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);

版本二:中文验证码 + TTF 真型字体(推荐)

<?php
session_start();

// 字符库:常用汉字 + 十六进制字符
$str = '芸芸众生绿水青山名胜古迹敞开心胸便会云蒸霞蔚快乐将永远伴随着你';
$chars = [];
for ($i = 0, $len = mb_strlen($str, 'UTF-8'); $i < $len; $i++) {
    $chars[] = mb_substr($str, $i, 1, 'UTF-8');
}

$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= (mt_rand(0, 1) === 0) ? $chars[mt_rand(0, count($chars)-1)] : dechex(mt_rand(0, 15));
}
$_SESSION['captcha'] = $code;

$img = imagecreatetruecolor(130, 40);
$bg = imagecolorallocate($img, 240, 240, 240);
imagefill($img, 0, 0, $bg);
$textColor = imagecolorallocate($img, 0, 0, 0);

// 需确保服务器有 MSYH.TTF (微软雅黑) 或其他 TTF 字体文件
$fontFile = __DIR__ . '/fonts/MSYH.TTF';
if (!is_file($fontFile)) {
    // 回退内置字体
    imagestring($img, 5, 20, 10, $code, $textColor);
} else {
    // TTF 绘制:大小、角度、x、y、颜色、字体文件、文本
    imagettftext($img, 20, mt_rand(-10, 10), 15, 30, $textColor, $fontFile, $code);
}

// 干扰线
for ($i = 0; $i < 5; $i++) {
    $color = imagecolorallocate($img, mt_rand(150, 255), mt_rand(150, 255), mt_rand(150, 255));
    imageline($img, mt_rand(0, 130), mt_rand(0, 40), mt_rand(0, 130), mt_rand(0, 40), $color);
}

// 干扰点
for ($i = 0; $i < 100; $i++) {
    $color = imagecolorallocate($img, mt_rand(100, 255), mt_rand(100, 255), mt_rand(100, 255));
    imagesetpixel($img, mt_rand(0, 130), mt_rand(0, 40), $color);
}

header('Content-Type: image/jpeg');
imagejpeg($img, null, 90);
imagedestroy($img);

前端验证交互

<img id="captcha" src="captcha.php" onclick="this.src='captcha.php?'+Date.now()" style="cursor:pointer">
<input name="captcha" placeholder="点击图片刷新">

后端验证

<?php
session_start();
if (strtoupper($_POST['captcha']) !== strtoupper($_SESSION['captcha'] ?? '')) {
    die('验证码错误');
}
// 通过,执行业务逻辑
unset($_SESSION['captcha']); // 用完即销毁,防重放

安全加固清单

  • ✅ 使用 random_bytes() 或 Random\Randomizer 生成随机字符(PHP 8.2+)
  • ✅ 字符倾斜、扭曲、波浪变形(需自定义 GD 绘制逻辑)
  • ✅ 干扰线/点密度自适应,避免过稀/过密
  • ✅ Session 存储加前缀 captcha_ 支持同页多验证码
  • ✅ 限制验证码接口频率(如 10 次/分钟/IP)
  • ✅ 重要操作(登录、注册、支付)必须验证码 + 短信/邮件二次验证

现代替代方案

方案优点缺点
GD 生成图片验证码零依赖、完全可控、兼容性好需维护字体、图片体积大、无障碍差
Google reCAPTCHA v3无感验证、风控强、免维护需外网、隐私合规、国内访问慢
极验/网易易盾等国内验证码行为分析、滑动拼图、国内加速商业收费、SDK 集成成本
Honeypot 隐藏表单零用户感知、极简仅防低级爬虫

对于中小项目,自建 GD 验证码依然是性价比最高的选择;关键业务建议接入成熟验证码服务。

copyright © 萬盛學電腦網 all rights reserved