Laravel11使用mews/captcha验证码系列教程,相比之前的版本设置有所变动。
验证码效果:
一、安装验证码扩展
composer require mews/captcha
二、注册验证码服务提供者
打开bootstrap/providers.php
添加如下代码,注册服务提供者
Mews\Captcha\CaptchaServiceProvider::class,
三、生成配置文件
使用composer命令,生成配置文件
php artisan vendor:publish
可以看到验证码的位于第8个序号,输入数字8,按下回车键
这里会在config文件夹下生成验证码配置文件captcha.php,我们在这里可以根据自己的喜好,设置验证码显示大小,字数等。
<?php return [ 'disable' => env('CAPTCHA_DISABLE', false), 'characters' => ['2', '3', '4', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'm', 'n', 'p', 'q', 'r', 't', 'u', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'M', 'N', 'P', 'Q', 'R', 'T', 'U', 'X', 'Y', 'Z'], 'default' => [ 'length' => 3, 'width' => 120, 'height' => 36, 'quality' => 90, 'math' => false, 'expire' => 60, 'encrypt' => false, ], 'math' => [ 'length' => 9, 'width' => 120, 'height' => 36, 'quality' => 90, 'math' => true, ], 'flat' => [ 'length' => 6, 'width' => 160, 'height' => 46, 'quality' => 90, 'lines' => 6, 'bgImage' => false, 'bgColor' => '#ecf2f4', 'fontColors' => ['#2c3e50', '#c0392b', '#16a085', '#c0392b', '#8e44ad', '#303f9f', '#f57c00', '#795548'], 'contrast' => -5, ], 'mini' => [ 'length' => 3, 'width' => 60, 'height' => 32, ], 'inverse' => [ 'length' => 5, 'width' => 120, 'height' => 36, 'quality' => 90, 'sensitive' => true, 'angle' => 12, 'sharpen' => 10, 'blur' => 2, 'invert' => true, 'contrast' => -5, ] ];
四、使用验证码
<div class="code"><img src="{{captcha_src()}}" width="116" height="36" onclick="this.src='{{captcha_src()}}'+Math.random()" id="radsrc"></div>
五、验证码判断
1、创建表单请求验证
php artisan make:request checkLogin
2、编写验证代码
<?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\Exceptions\HttpResponseException; class checkLogin extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'yzm' => 'sometimes|required|captcha', ]; } /** * 获取已定义验证规则的错误消息。 * * @return array */ public function messages() { return [ 'yzm.required' => '验证码不能为空', 'yzm.captcha' => '验证码错误', ]; } // ajax返回 public function failedValidation(Validator $validator) { throw (new HttpResponseException(response()->json([ 'code' => 500, 'msg' => $validator->errors()->first(), ], 200))); } }
3、对验证码是否正确判断
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\checkLogin; use Illuminate\Support\Facades\DB; class LoginController extends Controller { /* * 登录 * */ public function index(checkLogin $request){ if ($request->isMethod('post')){ //其他验证代码.... } } }
这里调用验证类会自动进行判断,判断验证码是否正确。
文章评论(0)