PHPackages                             solution-forest/laravel-math-captcha - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. solution-forest/laravel-math-captcha

ActiveLibrary[Security](/categories/security)

solution-forest/laravel-math-captcha
====================================

A simple math-based CAPTCHA package for Laravel with image generation to prevent AI/OCR bypass

v0.0.2(1mo ago)211MITPHPPHP ^8.2CI passing

Since Nov 28Pushed 1mo agoCompare

[ Source](https://github.com/solutionforest/laravel-math-captcha)[ Packagist](https://packagist.org/packages/solution-forest/laravel-math-captcha)[ RSS](/packages/solution-forest-laravel-math-captcha/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (10)Versions (5)Used By (0)

Laravel Math CAPTCHA
====================

[](#laravel-math-captcha)

[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)[![PHP Version](https://camo.githubusercontent.com/0f16581d1180dbfd4c0e13166ec1267d4ad2f2fab8281ea6d6b284cf5c65d921/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d626c75652e737667)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/a6874a9d36788f06a2b9c7b9a5559e19cf4dd5d445b327ba6e2038bf704f57c7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31312e7825323025374325323031322e782d7265642e737667)](https://laravel.com)

A simple, self-hosted math-based CAPTCHA package for Laravel with image generation to prevent AI/OCR bypass. No external API dependencies required.

> **Note:** This package was generated with the assistance of AI (Claude by Anthropic).

Table of Contents
-----------------

[](#table-of-contents)

- [Screenshot](#screenshot)
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage](#usage)
    - [Generate a CAPTCHA](#generate-a-captcha)
    - [Verify a CAPTCHA](#verify-a-captcha)
    - [Using the Facade](#using-the-facade)
    - [Using Dependency Injection](#using-dependency-injection)
    - [Using the Validation Rule](#using-the-validation-rule)
- [Frontend Integration](#frontend-integration)
    - [Livewire Example](#livewire-example)
    - [React Example](#react-example)
    - [Vue Example](#vue-example)
    - [Vanilla JavaScript Example](#vanilla-javascript-example)
- [Configuration](#configuration)
    - [Image Settings](#image-settings)
    - [Math Operations](#math-operations)
    - [Visual Customization](#visual-customization)
    - [Route Configuration](#route-configuration)
- [API Reference](#api-reference)
- [Security Considerations](#security-considerations)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)

Screenshot
----------

[](#screenshot)

[![CAPTCHA Example](docs/captcha-example.png)](docs/captcha-example.png)

*Example of a generated math CAPTCHA image with noise and distortion*

Features
--------

[](#features)

- **Math-based CAPTCHA** - Generates simple arithmetic problems (addition, subtraction, multiplication)
- **Image Generation** - Renders CAPTCHA as PNG image with anti-OCR measures:
    - Random noise lines and dots
    - Character position variations
    - Multiple text colors
    - Curved distortion line
- **Self-hosted** - No external API calls, no third-party dependencies
- **Configurable** - Customize difficulty, appearance, and behavior
- **Laravel Integration** - Service provider auto-discovery, Facade support, validation rule
- **One-time Use** - Each CAPTCHA token is invalidated after verification attempt
- **Cache-based Storage** - Uses Laravel's cache system for token storage

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 11.x or 12.x
- GD extension (for image generation)

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require solution-forest/laravel-math-captcha
```

The package will automatically register its service provider via Laravel's package auto-discovery.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

To customize the CAPTCHA settings, publish the configuration file:

```
php artisan vendor:publish --tag=math-captcha-config
```

This will create a `config/math-captcha.php` file in your application.

Quick Start
-----------

[](#quick-start)

1. **Install the package:**

    ```
    composer require solution-forest/laravel-math-captcha
    ```
2. **Add CAPTCHA to your form (frontend):**

    ```

    Refresh

    async function refreshCaptcha() {
        const response = await fetch('/captcha');
        const data = await response.json();
        document.getElementById('captcha-image').src = data.image;
        document.getElementById('captcha-token').value = data.token;
    }
    refreshCaptcha(); // Load initial CAPTCHA

    ```
3. **Verify in your controller (backend):**

    ```
    use SolutionForest\MathCaptcha\Contracts\CaptchaGenerator;

    public function store(Request $request, CaptchaGenerator $captcha)
    {
        if (!$captcha->verify($request->captcha_token, $request->captcha_answer)) {
            return back()->withErrors(['captcha' => 'Incorrect answer']);
        }

        // Process form...
    }
    ```

Usage
-----

[](#usage)

### Generate a CAPTCHA

[](#generate-a-captcha)

The package automatically registers a route at `/captcha` (GET) that returns JSON:

```
{
    "token": "abc123def456...",
    "image": "data:image/png;base64,iVBORw0KGgo..."
}
```

- `token` - A unique 32-character string to identify this CAPTCHA challenge
- `image` - Base64-encoded PNG image data URI that can be used directly in ``

### Verify a CAPTCHA

[](#verify-a-captcha)

Send the `token` and user's `answer` to your backend for verification. The verification:

- Returns `true` if the answer is correct
- Returns `false` if the answer is wrong or the token is invalid/expired
- Invalidates the token after the first verification attempt (one-time use)

### Using the Facade

[](#using-the-facade)

```
use SolutionForest\MathCaptcha\Facades\MathCaptcha;

// Generate a new CAPTCHA
$captcha = MathCaptcha::generate();
// Returns: [
//     'token' => 'abc123...',
//     'image' => 'data:image/png;base64,...'
// ]

// Verify an answer
$isValid = MathCaptcha::verify($token, $userAnswer);
// Returns: true or false
```

### Using Dependency Injection

[](#using-dependency-injection)

```
use SolutionForest\MathCaptcha\Contracts\CaptchaGenerator;

class ContactController extends Controller
{
    public function store(Request $request, CaptchaGenerator $captcha)
    {
        // Verify the CAPTCHA
        $isValid = $captcha->verify(
            $request->input('captcha_token'),
            $request->input('captcha_answer')
        );

        if (!$isValid) {
            return back()->withErrors(['captcha' => 'Invalid CAPTCHA answer. Please try again.']);
        }

        // CAPTCHA is valid, process the form...
    }
}
```

### Using the Validation Rule

[](#using-the-validation-rule)

For cleaner validation, use the built-in validation rule:

```
use SolutionForest\MathCaptcha\Rules\ValidCaptcha;

public function store(Request $request)
{
    $request->validate([
        'name' => 'required|string',
        'email' => 'required|email',
        'captcha_answer' => ['required', new ValidCaptcha()],
    ]);

    // Validation passed, process the form...
}
```

The rule automatically looks for `captcha_token` and `captcha_answer` fields. You can customize the field names:

```
new ValidCaptcha(
    tokenField: 'my_captcha_token',
    answerField: 'my_captcha_answer'
)
```

Frontend Integration
--------------------

[](#frontend-integration)

### Livewire Example

[](#livewire-example)

**Livewire Component (app/Livewire/ContactForm.php):**

```
