Home  >  Article  >  PHP Framework  >  laravel implements Google click image verification code [recommended]

laravel implements Google click image verification code [recommended]

藏色散人
藏色散人forward
2021-12-15 15:22:502088browse

The following tutorial column of Laravel will introduce how to use laravel-gridCaptcha to locally generate a verification code similar to Google click image. I hope it will be helpful to everyone!

[Extension Recommendation] Use laravel-gridCaptcha to locally generate a verification code similar to Google's dot image

Introduction

laravel-gridCaptcha Generates a small extension similar to the Google click image verification code, because PHP is now large The partially generated verification code is easy for malicious actors to identify, while this set of small extensions is very simple, but requires deep machine learning for robots, which increases the cost of malicious attacks. However, this set of small extensions is different. Since Google verification code requires machine learning, you only need to configure the corresponding files locally. Because the generated verification code images are generated by reading files, it is recommended to use Redis for caching. The code uses caching by default.

ps: 如有不足之处,欢迎大佬提出修改意见。

Github: https://github.com/deleteDB/laravel-captcha-grid

Packagist: https://packagist.org/packages/deletedb/laravel-captcha-grid

Preview

laravel implements Google click image verification code [recommended]

##Installation

Support Laravel 8 or above:

 composer require deletedb/laravel-captcha-grid

Configuration item description

    Publish configuration file
php artisan vendor:publish --provider="Deletedb\Laravel\Providers\LaravelServiceProvider"
config/gridcaptcha.php
return [
    //生成验证码图片配置
    'image' => [
        //验证码图片路径
        'path' => env('GRID_CAPTCHA_IMAGE_PATH', storage_path('gridcaptcha\image')),
        //从验证码图片路径中获取的文件后缀名
        'suffix' => env('GRID_CAPTCHA_IMAGE_SUFFIX', 'jpg'),
        //生成验证码质量
        'quality' => env('GRID_CAPTCHA_IMAGE_QUALITY', 70),
        //生产验证码宽
        'wide' => env('GRID_CAPTCHA_IMAGE_WIDE', 300),
        //生产验证码高
        'high' => env('GRID_CAPTCHA_IMAGE_HIGH', 300),
    ],
    //验证码配置
    'captcha' => [
        //生成的验证码过期时间 单位秒
        'validity' => env('GRID_CAPTCHA_IMAGE_VALIDITY', 180),
        //验证码缓存的key
        'cache_key' => env('GRID_CAPTCHA_IMAGE_CACHE_KEY', 'grid_captcha'),
        //验证码生成的key长度
        'key_length' => env('GRID_CAPTCHA_IMAGE_KEY_LENGTH', 64),
        //自定义效验验证码key字段
        'key_string' => env('GRID_CAPTCHA_IMAGE_KEY_STRING', 'captcha_key'),
        //自定义效验验证码code字段
        'code_string' => env('GRID_CAPTCHA_IMAGE_CODE_STRING', 'captcha_code'),
    ],];

Use

  • to generate the verification code

    <?php namespace App\Http\Controllers;class TestController extends Controller{
      /**
       * 辅助函数生成验证码
       * @return array
       */
      public function helpers()
      {
          return grid_captcha([
              &#39;mobile&#39; => '100xxxxx121'
          ]);
      }
    
      /**
       * 门面方式生成验证码
       * @return array
       */
      public function facade()
      {
          return \Deletedb\Laravel\Facades\GridCaptcha::get([
              'mobile' => '100xxxxx121'
          ]);
      }
    
      /**
       * 对象方式生成验证码
       * @return array
       */
      public function object()
      {
          $captcha = new \Deletedb\Laravel\GridCaptcha();
          return $captcha->get([
              'mobile' => '100xxxxx121'
          ]);
      }}
- 生成结果```json5{
  "hint": "猴子",//提示文本
  "captcha_key": "Qh8kHYF4C....",//验证码key
  "image": "data:image/jpeg;base64,/9j/...."//base64验证码图片 -- 前端渲染显示}
    Verify the verification code
 <!--

生成的是一个九宫格图片,前端需要渲染图片,并且生成九个div用于记录用户点击的宫格位置,宫格位置从 0 开始,当点击到四位的时候返回给后端进行效验 ,因为前端技术拙劣我就不放例子了欢迎大佬补充。

大概思路:
-->
<div>
    <!-- img 显示的是返回的验证码图片-->
    <img  alt="laravel implements Google click image verification code [recommended]" >
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
Effect:


laravel implements Google click image verification code [recommended]

<?php namespace App\Http\Controllers;use Illuminate\Http\Request;class TestController extends Controller{

    /**
     * 辅助函数方式效验
     * @param Request $request
     * @return array|false|\Illuminate\Http\JsonResponse
     */
    public function helpersCheck(Request $request)
    {
        /**
         * 传参效验
         */
        if ($captcha_data = grid_captcha()->check('Qh8kHYF4C....', '1540') === false) {
            return response()->json(['message' => '验证码错误', 'code' => 401]);
        }

        /**
         * 传递 Request 对象效验
         */
        if ($captcha_data = grid_captcha()->checkRequest($request)) {
            return response()->json(['message' => '验证码错误', 'code' => 401]);
        }

        return $captcha_data;
    }

    /**
     * 门面方式效验
     * @param Request $request
     * @return array|false|\Illuminate\Http\JsonResponse
     */
    public function facadeCheck(Request $request)
    {
        /**
         * 传参效验
         */
        if ($captcha_data = \Deletedb\Laravel\Facades\GridCaptcha::check('Qh8kHYF4C....', '1540') === false) {
            return response()->json(['message' => '验证码错误', 'code' => 401]);
        }

        /**
         * 传递 Request 对象效验
         */
        if ($captcha_data = \Deletedb\Laravel\Facades\GridCaptcha::checkRequest($request)) {
            return response()->json(['message' => '验证码错误', 'code' => 401]);
        }

        return $captcha_data;
    }

    /**
     * 对象方式效验
     * @param Request $request
     * @return array|false|\Illuminate\Http\JsonResponse
     */
    public function objectCheck(Request $request)
    {
        $captcha = new \Deletedb\Laravel\GridCaptcha();
        /**
         * 传参效验
         */
        if ($captcha_data = $captcha->check('Qh8kHYF4C....', '1540') === false) {
            return response()->json(['message' => '验证码错误', 'code' => 401]);
        }

        /**
         * 传递 Request 对象效验
         */
        if ($captcha_data = $captcha->checkRequest($request)) {
            return response()->json(['message' => '验证码错误', 'code' => 401]);
        }

        return $captcha_data;
    }}

    //效验完成正确后 您可以进行业务逻辑处理,比如可以获取到上方设置在验证码中的数据 如:上方设置的是手机号,您这里可以获取验证码中的手机号,当效验成功发送短信验证码等...
  • Successfully returned: The data you passed when generating the verification is returned, and empty is returned by default Array

  • Validation failure returns: false

    {
        "mobile" : "100xxxxx121"}
  • Localization prompt

    resources/lang/zh_CN/grid-captcha.php
    <?php 
//一个图片目录对应一个提示
return [
  'banmaxian' => '斑马线',
  'gongjiaoche' => '公交车',
  'heiban' => '黑板',
  'honglvdeng' => '红绿灯',
  'hongzao' => '红枣',
  'houzi' => '猴子',
  'qianbi' => '铅笔',
  'shutiao' => '薯条',
  'xiaofangshuan' => '消防栓',
  'zhenglong' => '蒸笼',];
  • Add a new verification code image

    Example: To add a new verification code type image of type

    pingguo, you need to add it to image.path in the configuration file. Create a directory named pingguo under the directory and store the picture files of related types in the pingguo directory. A new type must have at least four pictures of related types, and the file name is not limited. , as long as the file suffix name is specified in the configuration file, it can be as follows:

    ─storage
      └─gridcaptcha
          └─image
              ├─pingguo
              │       1.jpg
              │       10.jpg
              │       11.jpg
              │       12.jpg
              │       13.jpg
  • "

    Special note

    because Reading files is a caching operation that consumes I/O, so I recommend using Redis for caching. This tool uses caching by default, and the cache contains the current verification code image directory information and images; to use Redis caching, you only need to add it to

    .envFile modificationCACHE_DRIVER=redis, and add Redis configuration; after adding a new category, it is recommended to delete the previous cache. If not deleted, it will be automatically updated after the cache expires.

    The above is the detailed content of laravel implements Google click image verification code [recommended]. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete