Laravel默认没有内置图片验证码功能,需要自己设置;
在Laravel中有很多图片验证码的库可以使用,本篇介绍其中之一:gregwar/captcha,这个库比较简单,在Laravel中比较常用。下面我们就来介绍下使用细节:
一、首先, composer.json中如下加入配置:
"require": {
...
"gregwar/captcha": "1.*" },
然后,已成习惯的命令:用cmd执行下面这条命令
composer update
二、在controller中使用:三、页面中使用://引用对应的命名空间 use Gregwar\Captcha\CaptchaBuilder; use Session; //图片验证码 public function captcha() { //生成验证码图片的Builder对象,配置相应属性 $builder = new CaptchaBuilder; //可以设置图片宽高及字体 $builder->build($width = 100, $height = 38, $font = null); //获取验证码的内容 $phrase = $builder->getPhrase(); //把内容存入session Session::flash('milkcaptcha', $phrase); //session()->flash('milkcaptcha',$phrase); //生成图片 header("Cache-Control: no-cache, must-revalidate"); header('Content-Type: image/jpeg'); $builder->output(); }
路由:Route::get('/yzm', 'UsersController@captcha')->name('yzm');
<div class="form-group"> <label for="password_confirmation">验证码:</label> <input type="password" name="password_confirmation" class="form-control" value="" style="width:100px"> <a href="javascript:void(0);"> <img src="{{ route('yzm') }}" οnclick="javascript:this.src='{{ route('yzm') }}?tm='+Math.random()" width="100px" height="38px"> </a> </div>