laravel图片验证码插件安装使用

这里选择使用 gregwar/captcha , github地址:https://github.com/Gregwar/Captcha

其它验证码: 

https://github.com/mewebstudio/captcha

 

环境: laravel 6.11.0

第一步: 安装插件

composer require gregwar/captcha

第二步: 导入类

use Gregwar\Captcha\CaptchaBuilder;

use Gregwar\Captcha\PhraseBuilder;

第三步: 定义路由

 Route::get('imgcode','IndexController@imgCode')->name('imgcode');

第四步: 定义生成验证码方法

 /*

    * 图片验证码

    */

    public function imgCode()

    { 

        $phrase = new PhraseBuilder;

        // 设置验证码位数

        $code = $phrase->build(4);

        // 生成验证码图片的Builder对象,配置相应属性

        $builder = new CaptchaBuilder($code, $phrase);

        // 设置背景颜色25,25,112

        $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();

        // 把内容存入session

        session()->put('CAPTCHA_IMG', $phrase);

 

        // 生成图片

        header('Cache-Control: no-cache, must-revalidate');

        header('Content-Type:image/jpeg');

        $builder->output();

    }

第五步: 前台网页代码编写

    <style>

      .changeimgcode{

        color:blue;

        cursor:pointer;

      }

    </style>

   

<img id="elimg" src="{{route('imgcode')}}" style="width:100px;height:38px" οnclick="this.setAttribute('src','/imgcode?random='+Math.random())">

 <span class="changeimgcode" id="changeimgcode" οncοntextmenu="return false;" onselectstart="return false">看不清换一换</span>

  <script>

 $('#changeimgcode').click(function(){

            $('#elimg').trigger('click');

          }) 

</script>

        

第六步: 登录加入验证码判断

            $captchaImg = session('CAPTCHA_IMG');

            $imgcode = $request->get('imgcode','');

            if(!$imgcode)

            {

                return $this->retError('缺少验证码');

            }

            if(!$captchaImg)

            {

                return $this->retError('验证码错误');

            }

            if(strtolower($captchaImg) != strtolower($imgcode))

            {

                return $this->retError('验证码错误');

            }

        // 能走到这, 放行

 效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值