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里面效果就是这样的:

如果前台要调用,也很简单,直接把这个接口返回的结果放到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">

效果如下: 

è¿éåå¾çæè¿°

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值