laravel 6.^ 验证码扩展包使用
2020年2月17日安装扩展包
我们将以第三方扩展包 mews/captcha 作为基础来实现 Laravel 中的验证码功能。
使用 Composer 安装:
1 |
$ composer require "mews/captcha:~3.0" |
运行以下命令生成配置文件 config/captcha.php
:
1 |
$ php artisan vendor:publish --provider='Mews\Captcha\CaptchaServiceProvider' |
我们可以打开配置文件,查看其内容:
config/captcha.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?php return [ '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' => 9, 'width' => 120, 'height' => 36, 'quality' => 90, 'math' => 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, ] ]; |
可以看到这些配置选项都非常通俗易懂,characters
选项是用来显示给用户的所有字符串,default
, flat
, mini
, inverse
分别是定义的四种验证码类型,你可以在此修改对应选项自定义验证码的长度、背景颜色、文字颜色等属性,在此不做过多叙述。
页面嵌入
此扩展包的使用分为两步:
- 前端展示 —— 生成验证码给用户展示,并收集用户输入的答案;
- 后端验证 —— 接收答案,检测用户输入的验证码是否正确。
前段
1 2 3 4 5 6 7 8 9 10 11 |
<div class="col-md-6"> <input id="captcha" class="form-control{{ $errors->has('captcha') ? ' is-invalid' : '' }}" name="captcha" required> <img class="thumbnail captcha mt-3 mb-2" src="{{ captcha_src('flat') }}" onclick="this.src='/captcha/flat?'+Math.random()" title="点击图片重新获取验证码"> @if ($errors->has('captcha')) <span class="invalid-feedback" role="alert"> <strong>{{ $errors->first('captcha') }}</strong> </span> @endif </div> |
后端验证
1 |
'captcha' => ['required', 'captcha'], |