Laravel quickly creates a verification code tool similar to Google verification code

Overview

laravel-gridCaptcha

Laravel quickly creates a verification code tool similar to Google verification code

laravel 快速创建一个类似于 Google 点图验证码的本地验证码扩展

介绍

laravel-gridCaptcha 生成类似于谷歌点图验证码的小扩展,因为现在PHP大部分生成的验证码,对于恶意者来说很容易识别,而这套小扩展很简单但是对于机器人来说需要进行深度的机器学习,恶意者攻击的成本也就增加了,但是这套小扩展不同于谷歌验证码需要机器学习,只需要在本地配置好相应的文件即可。因为生成的验证码图片都是读取文件进行生成,所以建议使用Redis进行缓存,代码默认有使用缓存。

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

预览

Preview

安装

支持 Laravel 8 以上版本:

 composer require deletedb/laravel-captcha-grid

配置项说明

  • 发布配置文件
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'),
    ],
];

使用

  • 生成验证码



namespace App\Http\Controllers;


class TestController extends Controller
{
    /**
     * 辅助函数生成验证码
     * @return array
     */
    public function helpers()
    {
        return grid_captcha([
            'mobile' => '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'
        ]);
    }
}
  • 生成结果
{
  "hint": "猴子",//提示文本
  "captcha_key": "Qh8kHYF4C....",//验证码key
  "image": "data:image/jpeg;base64,/9j/...."//base64验证码图片 -- 前端渲染显示
}
  • 效验验证码
">
 
<div>
    
    <img src="data:image/jpeg;base64...." width="300" height="300" alt="" style="display: block;">
    <div id="0">div>
    <div id="1">div>
    <div id="2">div>
    <div id="3">div>
    <div id="4">div>
    <div id="5">div> <div id="6">div> <div id="7">div> <div id="8">div> div>
  • 效果: Preview





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;
    }
}

    //效验完成正确后 您可以进行业务逻辑处理,比如可以获取到上方设置在验证码中的数据 如:上方设置的是手机号,您这里可以获取验证码中的手机号,当效验成功发送短信验证码等...
  • 效验成功返回: 返回的是您在生成验证时传递的数据,默认返回空数组
  • 效验失败返回: false
{
  "mobile" : "100xxxxx121"
}
  • 本地化提示
resources/lang/zh_CN/grid-captcha.php

//一个图片目录对应一个提示
return [
    'banmaxian' => '斑马线',
    'gongjiaoche' => '公交车',
    'heiban' => '黑板',
    'honglvdeng' => '红绿灯',
    'hongzao' => '红枣',
    'houzi' => '猴子',
    'qianbi' => '铅笔',
    'shutiao' => '薯条',
    'xiaofangshuan' => '消防栓',
    'zhenglong' => '蒸笼',
];
  • 新增验证码图片

    例:新增一个类型为 pingguo 验证码类型的图片,需要在配置文件中的 image.path 目录下创建名为 pingguo 的目录并且把相关类型的图片文件存放在 pingguo 目录,新增一个类型至少要有四张相关类型的图片,不限制文件名,只要文件后缀名是配置文件中指定的即可如下:

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

特别说明

因为读取文件是缓存消耗I/O的操作所以我推荐使用Redis进行缓存,此工具默认使用了缓存,缓存有当前验证码图片目录信息、图片;使用Redis缓存只需要在 .env 文件修改 CACHE_DRIVER=redis ,并且添加Redis配置即可;在添加新分类之后建议删除之前的缓存,如果不进行删除将在缓存过期后自动更新。

License

MIT

You might also like...
thinkphp6 quickly creates a verification code tool similar to Google verification code
thinkphp6 quickly creates a verification code tool similar to Google verification code

tp-gridCaptcha thinkphp6 quickly creates a verification code tool similar to Google verification code thinkphp6 快速创建一个类似于 Google 点图验证码的本地验证码扩展 介绍 tp-g

Webman quickly creates a verification code tool similar to Google verification code
Webman quickly creates a verification code tool similar to Google verification code

webman-captcha-grid webman quickly creates a verification code tool similar to Google verification code webman 快速创建一个类似于 Google 点图验证码的本地验证码扩展 介绍 webma

An issue tracking tool based on laravel+reactjs for small and medium-sized enterprises, open-source and free, similar to Jira.
An issue tracking tool based on laravel+reactjs for small and medium-sized enterprises, open-source and free, similar to Jira.

ActionView English | 中文 An issue tracking tool based on php laravel-framework in back-end and reactjs+redux in front-end, it's similar to Jira. You co

An issue tracking tool based on hyperf+reactjs for small and medium-sized enterprises, open-source and free, similar to Jira.
An issue tracking tool based on hyperf+reactjs for small and medium-sized enterprises, open-source and free, similar to Jira.

介绍 本项目以 actionview 为蓝本,使用 Hyperf 框架进行重写。 本项目为 Hyperf 框架的 DEMO 项目 原 ActionView 介绍 English | 中文 一个类Jira的问题需求跟踪工具,前端基于reactjs+redux、后端基于php laravel-frame

A simple tool that I share with you. This tool serves to make conversions from text to audio Google Translate.

A simple tool that I share with you. This tool serves to make conversions from text to audio Google Translate. You can download this conversion 100% for free. Good luck.

 Low code , Zero Configuration ORM that creates models, config, database and tables on the fly.
Low code , Zero Configuration ORM that creates models, config, database and tables on the fly.

🚀 ARCA ORM 🔥 Low code , Zero Configuration ORM that creates models, config, database and tables on the fly. 🔥 🇮🇳 Made in India 🇮🇳 Complete docu

Manage redirects using database rules. Rules are intended to be very similar to Laravel default routes, so syntax is pretty easy to comprehend.

Laravel DB redirector Manage HTTP redirections in Laravel using database Manage redirects using database rules. Rules are intended to be very similar

Littlelink admin is an admin panel for littlelink that provides you a website similar linktree.

⚙️ LittleLink Admin LittleLink Admin is an admin panel for littlelink that provides you a website similar linktree. 📑 Features creating a link page w

Littlelink admin is an admin panel for littlelink that provides you a website similar linktree.

LittleLink Admin is an admin panel for littlelink that provides you a website similar linktree.

Get estimated read time of an article. Similar to medium.com's "x min read". Multilingual including right-to-left written languages. Supports JSON, Array and String output.

Read Time Calculates the read time of an article. Output string e.g: x min read or 5 minutes read. Features Multilingual translations support. Static

This package is aimed to be a simplistic PHP workflow package that works in a similar fashion to GitHub Actions.

Workflow This package is aimed to be a simplistic PHP workflow package that works in a similar fashion to GitHub Actions. Installation To install this

A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.
A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Desarolla2 Cache A simple cache library, implementing the PSR-16 standard using immutable objects. Caching is typically used throughout an applicatito

LittleLink Custom provides you with a website similar to Linktree. Many social media platforms only allow you to add one link
LittleLink Custom provides you with a website similar to Linktree. Many social media platforms only allow you to add one link

LittleLink Custom is a fork of LittleLink Admin with a set goal of making the admin panel easier to use and setup, for inexperienced and first-time users, with the addition of many custom features themed around customization for the individual user's, LittleLink pages.

A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.
A simple cache library. Implements different adapters that you can use and change easily by a manager or similar.

Desarolla2 Cache A simple cache library, implementing the PSR-16 standard using immutable objects. Caching is typically used throughout an applicatito

A tool for quickly measuring the size of a PHP project.

PHPLOC phploc is a tool for quickly measuring the size and analyzing the structure of a PHP project. Installation This tool is distributed as a PHP Ar

A tool that allows to quickly export data from Magento 1 and Magento 2 store and import it back into Magento 2

Simple Import / Export tool A tool that allows to quickly export data from Magento 1 and Magento 2 store and import it back into Magento 2. Table data

Creates an 'artisan workflow:make' command to scaffold out a number of useful GitHub actions workflows for Laravel

Laravel workflow generator This creates a make:workflow artisan command to scaffold out a number of useful GitHub actions workflows for Laravel. Insta

Creates repositories for Laravel models

##Repositories Maker## Repository pattern is an abstraction layer for your models. Instead of writing tones of duplicated queries in your controllers.

Laravel-hours-helper - Creates a Collection of times with a given interval.

Laravel Hours Helper With laravel-hours-helper you can create a collection of dates and/of times with a specific interval (in minutes) for a specific

Owner
delete DB Flee
delete DB Flee
Google reCAPTCHA Helper

Google reCAPTCHA Helper Simple Google reCAPTCHA Helper Contact & Support If any question & request, please contact following information Name Email Sk

Hung Nguyen 1 Jun 7, 2022
[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Validation Library The validation library in CakePHP provides features to build validators that can validate arbitrary arrays of data with eas

CakePHP 39 Oct 11, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
高性能的验证器组件(Validation),适用于 Hyperf 或 Laravel 框架,可获得数百倍的性能提升

验证器 简介 兼容 Hyperf/Laravel Validation 规则 部分场景可获得约 500 倍性能提升 验证器可多次复用不同数据,无状态设计 规则可全局复用 智能合并验证规则 安装 环境要求 PHP >= 8.0 mbstring 扩展 ctype 扩展 安装命令 composer re

KK集团 80 Dec 9, 2022
Custom Laravel Validator for combined unique indexes

unique_with Validator Rule For Laravel This package contains a variant of the validateUnique rule for Laravel, that allows for validation of multi-col

Felix Kiss 383 Oct 18, 2022
Extension for the Laravel validation class

Intervention Validation Intervention Validation is an extension library for Laravel's own validation system. The package adds rules to validate data l

null 370 Dec 30, 2022
Extra validation rules for dealing with images in Laravel 5.

Image-Validator Extra validation rules for dealing with images in Laravel 5. NOTE: As of Laravel version 5.2, there are now built-in validation rules

Colin Viebrock 223 Jun 16, 2022
Laravel Validation Service

Laravel Validation Service Installation Add "prettus/laravel-repository": "1.1.*" to composer.json "prettus/laravel-validation": "1.1.*" Create a vali

Anderson Andrade 398 Nov 25, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
A re-write of rakit/validation, a standalone validation library inspired by Laravel Validation

Somnambulist Validation This is a re-write of rakit/validation, a standalone validator like Laravel Validation. In keeping with rakit/validation, this

Somnambulist Tech 18 Dec 14, 2022