这里选择使用 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','[email protected]')->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('验证码错误');

            }

        // 能走到这, 放行

 效果图:

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

相关文章:

  • 2021-05-24
  • 2021-12-27
  • 2021-09-08
  • 2021-11-17
  • 2022-12-23
  • 2021-09-08
  • 2021-08-04
  • 2021-12-11
猜你喜欢
  • 2021-06-30
  • 2022-02-22
  • 2021-09-05
  • 2021-09-14
  • 2021-10-07
  • 2021-08-28
相关资源
相似解决方案