superpx-cn/laravel-captcha

Laravel 验证码包

安装: 36

依赖者: 0

建议者: 0

安全性: 0

星标: 1

关注者: 0

分支: 450

类型:

1.0.2 2023-02-23 07:54 UTC

This package is auto-updated.

Last update: 2024-09-23 11:26:46 UTC


README

支持 Laravel 5/6/7/8/9

一个简单的Laravel 图形验证码服务提供商。

预览

Preview

安装

使用 composer 安装

composer require superpx-cn/laravel-captcha

使用

要使用 Captcha 服务提供者,您必须在启动 Laravel 应用程序时注册该提供者。这主要有两种方法。

config/app.php 中找到 providers 键并注册 Captcha 服务提供者。

    'providers' => [
        // ...
        'Mews\Captcha\CaptchaServiceProvider',
    ]

对于 Laravel 5.1+

    'providers' => [
        // ...
        Mews\Captcha\CaptchaServiceProvider::class,
    ]

config/app.php 中找到 aliases 键。

    'aliases' => [
        // ...
        'Captcha' => 'Mews\Captcha\Facades\Captcha',
    ]

对于 Laravel 5.1+

    'aliases' => [
        // ...
        'Captcha' => Mews\Captcha\Facades\Captcha::class,
    ]

配置

自定义设置

要使用自己的设置,发布配置。

$ php artisan vendor:publish

config/captcha.php

return [
    'default'   => [
        'length'    => 5,
        'width'     => 120,
        'height'    => 36,
        'quality'   => 90,
        'math'      => true,  //Enable Math Captcha
        'expire'    => 60,    //Captcha expiration
    ],
    // ...
];

禁用验证

要禁用验证码验证,使用 CAPTCHA_DISABLE 环境变量。例如 .env 配置

CAPTCHA_DISABLE=true

示例使用

会话模式

    // [your site path]/Http/routes.php
    Route::any('captcha-test', function() {
        if (request()->getMethod() == 'POST') {
            $rules = ['captcha' => 'required|captcha'];
            $validator = validator()->make(request()->all(), $rules);
            if ($validator->fails()) {
                echo '<p style="color: #ff0000;">Incorrect!</p>';
            } else {
                echo '<p style="color: #00ff30;">Matched :)</p>';
            }
        }
    
        $form = '<form method="post" action="captcha-test">';
        $form .= '<input type="hidden" name="_token" value="' . csrf_token() . '">';
        $form .= '<p>' . captcha_img() . '</p>';
        $form .= '<p><input type="text" name="captcha"></p>';
        $form .= '<p><button type="submit" name="check">Check</button></p>';
        $form .= '</form>';
        return $form;
    });

无状态模式

您可以使用 助手函数 captcha() 来生成一个验证码 captcha() 方法将返回一个数组,其中包含:

  • sensitive
  • key: 验证码的标识
  • img: 验证码的 base64 编码

并使用此方法检查验证码

    // key is the one that you got from json response
    // fix validator
    // $rules = ['captcha' => 'required|captcha_api:'. request('key')];
    $rules = ['captcha' => 'required|captcha_api:'. request('key') . ',math'];
    $validator = validator()->make(request()->all(), $rules);
    if ($validator->fails()) {
        return response()->json([
            'message' => 'invalid captcha',
        ]);

    } else {
        //do the job
    }

返回图片

captcha();

Captcha::create();

返回 URL

captcha_src();

Captcha::src('default');

返回 HTML

captcha_img();

Captcha::img();

要使用不同的配置

captcha_img('flat');

Captcha::img('inverse');

等等。

基于 Intervention Image

^_^

链接