推荐使用 mews/captcha 替代已弃用的 gregwar/captcha,因其持续维护、兼容 Laravel 10+ 和 PHP 8.2+;需正确发布配置、检查 bgColor 格式、确认缓存与 GD 环境。

Composer 安装图形验证码库本身没问题,但直接装 gregwar/captcha 或 mews/captcha 很可能踩坑——它们要么已弃用,要么不兼容 Laravel 10+ / PHP 8.2+,要么 require 冲突卡死安装。
为什么 composer require gregwar/captcha 常失败
这个包最后更新是 2021 年,PHP 8.1+ 的类型系统和 GD 扩展变动让它在新环境报错:Declaration of Gregwar\Captcha\CaptchaBuilder::build() must be compatible with Gregwar\Captcha\PhraseBuilderInterface::build()。它还硬依赖过时的 symfony/http-foundation v4,和现代 Laravel 的 v6+ 冲突。
常见错误现象:
Root composer.json requires gregwar/captcha ^2.1 -> found gregwar/captcha[v2.1.0, ..., v2.1.2] but these were not loaded- 安装后调用
CaptchaBuilder::create()报致命错误,GD 模块检测失败(即使php -m | grep gd显示已启用)
Laravel 9/10 推荐用 mews/captcha 的正确姿势
它目前维护活跃(2024 年仍有提交),适配 Laravel 10 和 PHP 8.2,但默认配置容易漏掉关键项,导致生成空白图或 500 错误。
实操建议:
- 运行
composer require mews/captcha(不要加版本号,让 Composer 自动选兼容版) - 发布配置:执行
php artisan vendor:publish --provider="Mews\Captcha\CaptchaServiceProvider",会生成config/captcha.php - 检查
config/captcha.php中的'default' => ['length' => 5],确保'bgColor'是数组格式(如[255, 255, 255]),不是字符串'#ffffff',否则 GD 渲染失败 - 如果用 Redis 缓存验证码,确认
'storage' => 'session'已改为'redis',且cache.store配置正确,否则验证时总提示“验证码错误”
手动生成验证码图片的最小可行代码
绕过 Laravel 的 facade 直接调用底层,能快速验证 GD 是否真正常工作,也方便调试路径、字体缺失等问题。
在 routes/web.php 里临时加一段测试路由:
Route::get('/test-captcha', function () {
$captcha = new \Mews\Captcha\CaptchaBuilder();
$captcha->build(150, 40, null, 20); // 宽、高、字体路径(null=内置)、字体大小
return response($captcha->get())->header('Content-Type', 'image/jpeg');
});
访问 /test-captcha,如果返回空白或报错:
- 检查
phpinfo()里 GD 模块是否启用,FreeType Support是否为 enabled(影响中文/字体渲染) - 确认
storage/fonts目录存在且可写,或传入绝对路径如base_path('resources/fonts/arial.ttf') - Linux 上常见问题:缺少
libfreetype6-dev,需apt install libfreetype6-dev后重编 PHP
真正麻烦的不是装不上,而是装上之后验证码不刷新、验证总失败、或者在队列/多服务器环境下 session 不同步——这些得看缓存驱动和 session 配置,不是换一个包就能解决的。










