PHPackages                             mrtolouei/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. mrtolouei/laravel-math-captcha

ActiveLibrary[Security](/categories/security)

mrtolouei/laravel-math-captcha
==============================

Single-use CAPTCHA for Laravel with anti-replay protection

v1.0.0(6mo ago)10MITPHPPHP ^8.1CI passing

Since Jan 24Pushed 6mo agoCompare

[ Source](https://github.com/mrtolouei/laravel-math-captcha)[ Packagist](https://packagist.org/packages/mrtolouei/laravel-math-captcha)[ RSS](/packages/mrtolouei-laravel-math-captcha/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (1)Dependencies (4)Versions (2)Used By (0)

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

[](#laravel-math-captcha)

[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![Tests](https://github.com/mrtolouei/laravel-math-captcha/actions/workflows/tests.yml/badge.svg)](https://github.com/mrtolouei/laravel-math-captcha/actions/workflows/tests.yml)[![Latest Stable Version](https://camo.githubusercontent.com/372dac25672a6828b0e485a958a51ba8ede0d71c0a02b952548ba1c1c74d362f/68747470733a2f2f706f7365722e707567782e6f72672f6d72746f6c6f7565692f6c61726176656c2d6d6174682d636170746368612f762f737461626c65)](https://packagist.org/packages/mrtolouei/laravel-math-captcha)

A **stateless, lightweight math-based CAPTCHA package for Laravel** that generates a simple arithmetic challenge as an image and verifies it via signed payloads.
No database, cache, or filesystem is required.

---

Table of contents
-----------------

[](#table-of-contents)

1. [Features](#features)
2. [Requirements](#requirements)
3. [Installation](#installation)
4. [Configuration](#configuration)
5. [Usage](#usage)
6. [Example Controller](#example-controller)
7. [Testing](#testing)
8. [Advanced Usage](#advanced-usage)
9. [Security Notes](#security-notes)
10. [Contributions](#contributions)
11. [License](#license)

---

Features
--------

[](#features)

- Stateless: no DB, cache, or filesystem dependency.
- Uses **Laravel APP\_KEY** for secure HMAC signing.
- Configurable math range and image appearance.
- Simple **one-time-use CAPTCHA** (answer embedded in signed hash).
- Ready for **Laravel 10+**.
- Fully testable with **PHPUnit**.

---

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

[](#requirements)

- PHP ≥ 8.1
- Laravel ≥ 10
- GD extension enabled (`php-gd`)
- Composer

---

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

[](#installation)

Install via Composer:

```
  composer require mrtolouei/laravel-math-captcha
```

Publish configuration file:

```
  php artisan vendor:publish --provider="Mrtolouei\MatchCaptcha\CaptchaServiceProvider" --tag="config"
```

This will create:

```
config/captcha.php

```

---

Configuration
-------------

[](#configuration)

**config/captcha.php** contains two main sections:

### Image

[](#image)

```
'image' => [
    'width'  => 160,           // Width in pixels
    'height' => 60,            // Height in pixels
    'font'   => 5,             // GD built-in font (1-5)
    'bg'     => [245,247,250], // Background color RGB
    'fg'     => [30,30,30],    // Foreground/text color RGB
],
```

### Math Expression

[](#math-expression)

```
'math' => [
    'min' => env('CAPTCHA_MATH_MIN', 1),  // Minimum number
    'max' => env('CAPTCHA_MATH_MAX', 9),  // Maximum number
],
```

- Increasing the `min`/`max` range makes CAPTCHA harder.
- You can also use `.env` for environment-specific values.

---

Usage
-----

[](#usage)

### Generating a CAPTCHA

[](#generating-a-captcha)

```
use Mrtolouei\MatchCaptcha\CaptchaManager;

$manager = new CaptchaManager();

$result = $manager->generate();

/*
$result is an instance of CaptchaGenerateResult:

$result->image // Base64-encoded PNG
$result->hash  // Signed payload with the answer
*/
```

### Display in Blade

[](#display-in-blade)

```

```

### Verifying CAPTCHA

[](#verifying-captcha)

```
$valid = $manager->verify($request->input('captcha_answer'), $request->input('captcha_hash'));

if ($valid) {
    // CAPTCHA passed
} else {
    // CAPTCHA failed
}
```

⚠ Note: This CAPTCHA is stateless, so there is no anti-replay mechanism. Each CAPTCHA is single-use in logic only; after verification, the hash can be reused unless you implement additional storage/cache.

---

Example Controller
------------------

[](#example-controller)

```
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mrtolouei\MatchCaptcha\CaptchaManager;

class ContactController extends Controller
{
    protected CaptchaManager $captcha;

    public function __construct(CaptchaManager $captcha)
    {
        $this->captcha = $captcha;
    }

    public function showForm()
    {
        $captcha = $this->captcha->generate();
        return view('contact.form', compact('captcha'));
    }

    public function submit(Request $request)
    {
        $request->validate([
            'captcha_answer' => 'required',
            'captcha_hash'   => 'required',
        ]);

        if (! $this->captcha->verify($request->captcha_answer, $request->captcha_hash)) {
            return back()->withErrors(['captcha_answer' => 'CAPTCHA verification failed.']);
        }

        // Process the form...
    }
}
```

---

Testing
-------

[](#testing)

This package uses PHPUnit 10 and Orchestra Testbench for Laravel integration.

Run tests:

```
    composer install
    vendor/bin/phpunit
```

### Unit Tests Covered

[](#unit-tests-covered)

- CAPTCHA generation returns valid image and hash.
- Correct answers pass verification.
- Wrong answers fail verification.
- Tampered hashes fail verification.
- Math expression respects configured `min`/`max`.

---

Advanced Usage
--------------

[](#advanced-usage)

- Customize image width, height, font, and colors via config.
- Adjust math difficulty by setting `.env` variables:

```
CAPTCHA_MATH_MIN=1
CAPTCHA_MATH_MAX=20

```

- Extend `CaptchaManager` to implement custom operators (e.g., multiplication).

---

Security Notes
--------------

[](#security-notes)

- The security of this CAPTCHA relies on Laravel `APP_KEY` secrecy.
- It is stateless: you may want to implement replay prevention using cache or DB if required.
- Increasing math range improves bot-resistance but may reduce readability.

---

Contributions
-------------

[](#contributions)

PRs, issues, stars are welcome!

- For bugs: open a GitHub issue.
- For features: fork and submit a PR.
- Follow PSR-12 coding style.

---

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

31

—

LowBetter than 65% of packages

Maintenance66

Regular maintenance activity

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

205d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/70100016?v=4)[Alireza Tolouei](/maintainers/mrtolouei)[@mrtolouei](https://github.com/mrtolouei)

---

Top Contributors

[![mrtolouei](https://avatars.githubusercontent.com/u/70100016?v=4)](https://github.com/mrtolouei "mrtolouei (4 commits)")

---

Tags

captchalaravel-captchamath-captchasecuritylaravelsecuritycaptchastatelesssingle useone-timeanti-replay

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mrtolouei-laravel-math-captcha/health.svg)

```
[![Health](https://phpackages.com/badges/mrtolouei-laravel-math-captcha/health.svg)](https://phpackages.com/packages/mrtolouei-laravel-math-captcha)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.9M110](/packages/mongodb-laravel-mongodb)[propaganistas/laravel-disposable-email

Disposable email validator

6023.2M7](/packages/propaganistas-laravel-disposable-email)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k161.4k2](/packages/mike-bronner-laravel-model-caching)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

46273.9k](/packages/harris21-laravel-fuse)[iazaran/smart-cache

Smart Cache is a caching optimization package designed to enhance the way your Laravel application handles data caching. It intelligently manages large data sets by compressing, chunking, or applying other optimization strategies to keep your application performant and efficient.

21114.2k](/packages/iazaran-smart-cache)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
