0
点赞
收藏
分享

微信扫一扫

Laravel5.5生成验证码与验证正确与否

第一步:引入gregwar/captcha包:

composer require gregwar/captcha

第二步:在帮助函数中创建函数:

use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Session;
class HelperController extends Controller {
//生成验证码
public function captcha($tmp) {
//生成验证码图片的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();
}

//验证注册码的正确与否
public function verifyCaptcha() {
$userInput = request('captcha');
if (Session::get('milkcaptcha') == $userInput) {
//用户输入验证码正确
return $this->outPutJson('', 200, '验证码正确!');
} else {
//用户输入验证码错误
return $this->outPutJson('', 301, '验证码输入错误!');
}
}
}

第三步:如果想要替换自己的验证码字体,可以在包内的Font文件夹内替换,按照格式命名即可。看这个源码就明白了,随机生成一个数字,字体命名格式如下:captcha4.ttf。一般自带的就够用了。

D:\phpStudy\WWW\api.douxiaoli.com\vendor\gregwar\captcha\Font\
if ($font === null) {
$font = __DIR__ . '/Font/captcha' . $this->rand(0, 8) . '.ttf';
}

在postman里面效果就是这样的:

Laravel5.5生成验证码与验证正确与否_html

如果前台要调用,也很简单,直接把这个接口返回的结果放到img标签里面就可以了:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>我是index.html</h1>
<img src="http://api.commas-studio.com/helper/captcha/11">

效果如下:
Laravel5.5生成验证码与验证正确与否_json_02


举报

相关推荐

0 条评论