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(3mo ago)10MITPHPPHP ^8.1CI passing

Since Jan 24Pushed 3mo 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 1mo 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

34

—

LowBetter than 77% of packages

Maintenance80

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

105d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/736fa5617032c5dbfb470d46a5f5c363dc4de7c368b36fae53d17e935df5adc3?d=identicon)[mrtolouei](/maintainers/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

[tzsk/otp

A secure, database-free One-Time Password (OTP) generator and verifier for PHP and Laravel.

241641.4k1](/packages/tzsk-otp)[dgtlss/warden

A Laravel package that proactively monitors your dependencies for security vulnerabilities by running automated composer audits and sending notifications via webhooks and email

8745.6k](/packages/dgtlss-warden)[ercsctt/laravel-file-encryption

Secure file encryption and decryption for Laravel applications

642.6k](/packages/ercsctt-laravel-file-encryption)

PHPackages © 2026

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