Laravel图片验证码(gregwar/captcha)
第一步:安装第三方扩展包
composer require gregwar/captcha
第二步:路由文件定义路由
Route::get('verify',[Verify::class,'verify'])->name('lo_verify');
第三步:编写验证码控制器代码(缓存名称此处使用配置文件的,可直接用固定的即可)
<?php namespace App\Http\Controllers; use Gregwar\Captcha\CaptchaBuilder; use Gregwar\Captcha\PhraseBuilder; use Illuminate\Support\Facades\Cache; class Verify extends Controller { public function verify(){ $phrase = new PhraseBuilder(); //设置验证码位数和图片显示字符串(参数为可选) $verify_num = $phrase->build(4,'123456789'); //生成验证码图片的build对象,配置相应属性 $builder = new CaptchaBuilder($verify_num, $phrase); //设置背景颜色 $builder->setBackgroundColor(34, 0, 45); //设置倾斜角度 $builder->setMaxAngle(25); //设置验证码后面最大行数 $builder->setMaxBehindLines(10); //设置验证码前面最大行数 $builder->setMaxFrontLines(10); //设置验证码颜色 $builder->setTextColor(230, 81, 175); //设置图片宽高和字体 $builder->build($width=150, $height=40, $font=null); //获取验证码内容 $phrase = $builder->getPhrase(); //>>把验证码内容存到缓存 10分钟过期 可根据需求自定义 $captcha_name = empty(config('cache.image-verify.name'))?'captcha-verify':config('cache.image-verify.name'); $captcha_expiration_time = empty(config('cache.image-verify.expiration-time'))?10:config('cache.image-verify.expiration-time') * 60; Cache::put(md5($captcha_name), $phrase, $captcha_expiration_time); return $builder->inline(); } }
第四步:页面调用
<div style="cursor: pointer;" title="点击更换验证码" class="captcha-verify"></div>
<input type="hidden" name="verify_url" value="{{ route('lo_verify') }}"> <!-- jQuery --> <script src="{{ asset('static/js/jquery-2.1.1.min.js') }}"></script> <script> $(function () { get_verify(); $('.captcha-verify').click(function () { get_verify(); }); }); function get_verify() { var url = $('input[name="verify_url"]').val(); $.get(url,function (data) { var html = '<img style="width: 130px;height: 45px;border-radius:3px;" src="'+data+'" alt="captcha" />'; $('.captcha-verify').html('').html(html) },'text') }</script>
第五步:结果展示

第六步:PHP验证验证码
//>>验证图片验证码是否正确 $captcha_name = empty(config('cache.image-verify.name'))?'captcha-verify':config('cache.image-verify.name'); if(strtolower($request->post('captcha')) != strtolower(Cache::get(md5($captcha_name)))){ return json_encode(array('success'=>'error', 'msg'=>'图片验证码不正确')); }

浙公网安备 33010602011771号