Laravel 12 实现验证码功能
Laravel 12 实现验证码功能
在 Laravel 12 中实现验证码功能可以通过多种方式,以下是几种常见的方法:
方法一:使用 Captcha 包(推荐)
- 首先安装
mews/captcha
包:
composer require mews/captcha
- 发布配置文件:
php artisan vendor:publish --provider="Mews\Captcha\CaptchaServiceProvider"
-
在
config/captcha.php
中配置验证码选项 -
在表单视图中添加验证码:
<div class="form-group"><label for="captcha">验证码</label>{!! captcha_img() !!}<input id="captcha" type="text" class="form-control" name="captcha" required>
</div>
- 在控制器中验证:
public function postRegister(Request $request)
{$this->validate($request, ['captcha' => 'required|captcha']);// 其他注册逻辑
}
方法二:使用 Google reCAPTCHA
- 安装 Google reCAPTCHA 包:
composer require google/recaptcha
- 在
.env
中添加:
RECAPTCHA_SITE_KEY=your_site_key
RECAPTCHA_SECRET_KEY=your_secret_key
- 在表单中添加:
<div class="g-recaptcha" data-sitekey="{{ env('RECAPTCHA_SITE_KEY') }}"></div>
<script src="https://www.google.com/recaptcha/api.js"></script>
- 在控制器中验证:
use ReCaptcha\ReCaptcha;public function validateCaptcha(Request $request)
{$recaptcha = new ReCaptcha(env('RECAPTCHA_SECRET_KEY'));$response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());if (!$response->isSuccess()) {// 验证失败处理}// 其他逻辑
}
方法三:自定义验证码(简单实现)
- 创建验证码生成路由:
Route::get('/captcha', function() {$image = imagecreatetruecolor(100, 40);$bgColor = imagecolorallocate($image, 255, 255, 255);$textColor = imagecolorallocate($image, 0, 0, 0);imagefilledrectangle($image, 0, 0, 100, 40, $bgColor);$code = substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 6);session(['captcha' => $code]);imagestring($image, 5, 20, 12, $code, $textColor);header('Content-Type: image/png');imagepng($image);imagedestroy($image);
});
- 在视图中使用:
<img src="/captcha" alt="CAPTCHA" onclick="this.src='/captcha?'+Math.random()">
<input type="text" name="captcha" required>
- 验证:
if ($request->input('captcha') !== session('captcha')) {return back()->withErrors(['captcha' => '验证码错误']);
}
注意事项
- 验证码应该有一定的复杂度,防止被机器识别
- 可以考虑添加干扰线、噪点等增加安全性
- 验证码应该有有效期限制(通常5-10分钟)
- 对于重要操作,建议使用更安全的验证方式如短信验证码
以上方法可以根据项目需求选择使用,第一种方法是最简单快捷的实现方式。