1、 安装依赖 composer require gregwar/captcha
2、使用
use GregwarCaptchaCaptchaBuilder; use DB; use Request; use Session; //生成验证码 public function captcha() { //生成验证码图片的Builder对象,配置相应属性 $builder = new CaptchaBuilder; //可以设置图片宽高及字体 $builder->build($width = 250, $height = 70, $font = null); //获取验证码的内容 $phrase = $builder->getPhrase(); //把内容存入session Session::flash('milkcaptcha', $phrase); //生成图片 header("Cache-Control: no-cache, must-revalidate"); header('Content-Type: image/jpeg'); $builder->output(); } /** * Show the form for creating a new resource. * * @return Response */ public function create_mes(Request $request) { extract($request::all()); if (Session::get('milkcaptcha') == $code) { //用户输入验证码正确 return Response::json(array('code' => 0, 'info' => 'ok')); } else { //用户输入验证码错误 return Response::json(array('code' => 2, 'info' => 'erro')); } $res = DB::insert('insert message (content,username,createtime,contract) values (?,?,now(),?)', [$content, $username, $contract]); return Response::json(array('code' => 0, 'info' => 'ok')); }
3、vue 端 , 提交失败或者成功都重新获取验证码
<img @click="changeCode()" class="vCode" ref="vCImg" :src="baseURL+'captcha'" /> changeCode() { let img = this.$refs.vCImg img.src = baseURL+'captcha?'+new Date().getTime(); } submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { bolosev.create_mes(this.message).then(res=>{ if (res.code==0){ this.$message.success("留言成功") this.changeCode() this.resetForm(formName) } else if (res.code==2) { this.$message.error("验证码有误") this.changeCode() }else this.$message.error("留言失败") }) } else { console.log('error submit!!'); return false; } }); },