PHPackages                             snipershady/ratelimiter - 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. snipershady/ratelimiter

ActiveLibrary

snipershady/ratelimiter
=======================

A free and easy-to-use rate limiter

v1.0.6(2mo ago)42.9k↓100%GPL-3.0-or-laterPHPPHP &gt;=8.2

Since Sep 28Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/snipershady/ratelimiter)[ Packagist](https://packagist.org/packages/snipershady/ratelimiter)[ Docs](https://www.spinfo.it)[ RSS](/packages/snipershady-ratelimiter/feed)WikiDiscussions main Synced today

READMEChangelog (7)Dependencies (5)Versions (9)Used By (0)

Rate Limiter
============

[](#rate-limiter)

[![PHP Version](https://camo.githubusercontent.com/d840cef9807c8f76051ad687841d67f4d830c84e0d83236968e53124ef6742d5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e322d3838393242462e737667)](https://php.net/)[![License](https://camo.githubusercontent.com/8b59d97f09166dc0016167b7b0cf9a5830ee03c63f582ebd7ed5848ad497f1ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d47504c2d2d332e302d626c75652e737667)](https://www.gnu.org/licenses/gpl-3.0.html)[![Packagist](https://camo.githubusercontent.com/55188d5d9a5f8286a1e72b9fbbd82c8ede3933f23855cde6b54ba145563ead00/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736e6970657273686164792f726174656c696d697465722e737667)](https://packagist.org/packages/snipershady/ratelimiter)

A free and easy-to-use rate limiter for PHP applications.

Context
-------

[](#context)

You need to limit network traffic access to a specific function in a specific timeframe. Rate limiting may help to stop some kinds of malicious activity such as brute force attacks, DDoS, and API abuse.

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

[](#installation)

```
composer require snipershady/ratelimiter
```

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

[](#requirements)

RequirementVersionPHP&gt;= 8.2ext-apcu\*ext-redis\*predis/predis^3.2### Debian / Ubuntu

[](#debian--ubuntu)

```
apt-get install php8.4-redis php8.4-apcu
# You can install php-redis and php-apcu module for the version you've installed on the system
# Minimum PHP version required: 8.2
```

### CLI Usage

[](#cli-usage)

For CLI usage, remember to enable APCu in your `php.ini`:

```
apc.enable_cli=1
```

Available Cache Backends
------------------------

[](#available-cache-backends)

BackendEnumDescriptionAPCu`CacheEnum::APCU`Local in-memory cache, no external dependenciesPredis`CacheEnum::REDIS`Redis via Predis library (pure PHP)PhpRedis`CacheEnum::PHP_REDIS`Redis via php-redis extension (C extension, better performance)API Reference
-------------

[](#api-reference)

### `isLimited(string $key, int $limit, int $ttl): bool`

[](#islimitedstring-key-int-limit-int-ttl-bool)

Check if a key has exceeded the rate limit.

ParameterTypeDescription`$key`stringUnique identifier for the rate limit (e.g., `__METHOD__`)`$limit`intMaximum number of attempts allowed`$ttl`intTime window in seconds**Returns:** `true` if the limit has been exceeded, `false` otherwise.

### `isLimitedWithBan(string $key, int $limit, int $ttl, int $maxAttempts, int $banTimeFrame, int $banTtl, ?string $clientIp): bool`

[](#islimitedwithbanstring-key-int-limit-int-ttl-int-maxattempts-int-bantimeframe-int-banttl-string-clientip-bool)

Check if a key has exceeded the rate limit, with progressive ban support for repeat offenders.

ParameterTypeDescription`$key`stringUnique identifier for the rate limit`$limit`intMaximum number of attempts allowed`$ttl`intBase time window in seconds`$maxAttempts`intMax violations before triggering a ban`$banTimeFrame`intTime window for counting violations`$banTtl`intExtended time window when banned`$clientIp`string|nullClient IP for per-client banning**Returns:** `true` if the limit has been exceeded, `false` otherwise.

### `clearRateLimitedKey(string $key): bool`

[](#clearratelimitedkeystring-key-bool)

Remove a rate limit key, resetting its counter.

ParameterTypeDescription`$key`stringThe key to clear**Returns:** `true` on success, `false` on failure.

Usage Examples
--------------

[](#usage-examples)

### Dependencies

[](#dependencies)

```
use Predis\Client;
use RateLimiter\Enum\CacheEnum;
use RateLimiter\Service\AbstractRateLimiterService;
```

### APCu Example

[](#apcu-example)

```
class Foo
{
    public function controllerYouWantToRateLimit(): Response
    {
        $limiter = AbstractRateLimiterService::factory(CacheEnum::APCU);
        $key = __METHOD__;  // Name of the function you want to rate limit
        $limit = 2;         // Maximum attempts before the limit
        $ttl = 3;           // Time window in seconds

        if ($limiter->isLimited($key, $limit, $ttl)) {
            throw new Exception("LIMIT REACHED: YOU SHALL NOT PASS!");
        }

        // ... your code
    }
}
```

### Redis Example (Predis)

[](#redis-example-predis)

```
class Foo
{
    public function controllerYouWantToRateLimit(): Response
    {
        $redis = new Client([
            'scheme' => 'tcp',
            'host' => '192.168.0.100',
            'port' => 6379,
            'persistent' => true,
        ]);

        $limiter = AbstractRateLimiterService::factory(CacheEnum::REDIS, $redis);
        $key = __METHOD__;
        $limit = 2;
        $ttl = 3;

        if ($limiter->isLimited($key, $limit, $ttl)) {
            throw new Exception("LIMIT REACHED: YOU SHALL NOT PASS!");
        }

        // ... your code
    }
}
```

### Redis Example (PhpRedis)

[](#redis-example-phpredis)

```
class Foo
{
    public function controllerYouWantToRateLimit(): Response
    {
        $redis = new \Redis();
        $redis->pconnect(
            '192.168.0.100',        // host
            6379,                   // port
            2,                      // connect timeout
            'persistent_id_rl'      // persistent_id
        );

        $limiter = AbstractRateLimiterService::factory(CacheEnum::PHP_REDIS, $redis);
        $key = __METHOD__;
        $limit = 2;
        $ttl = 3;

        if ($limiter->isLimited($key, $limit, $ttl)) {
            throw new Exception("LIMIT REACHED: YOU SHALL NOT PASS!");
        }

        // ... your code
    }
}
```

### Rate Limit with Ban

[](#rate-limit-with-ban)

Use this when you want to progressively punish repeat offenders with longer timeouts.

```
class Foo
{
    public function controllerYouWantToRateLimit(): Response
    {
        $redis = new Client([
            'scheme' => 'tcp',
            'host' => '192.168.0.100',
            'port' => 6379,
            'persistent' => true,
        ]);

        $limiter = AbstractRateLimiterService::factory(CacheEnum::REDIS, $redis);

        $key = __METHOD__;
        $limit = 1;             // Max attempts before limit
        $ttl = 2;               // Base time window (seconds)
        $maxAttempts = 3;       // Violations before ban kicks in
        $banTimeFrame = 4;      // Time window for counting violations
        $banTtl = 10;           // Extended timeout when banned
        $clientIp = $_SERVER['REMOTE_ADDR'] ?? null;

        if ($limiter->isLimitedWithBan($key, $limit, $ttl, $maxAttempts, $banTimeFrame, $banTtl, $clientIp)) {
            throw new Exception("LIMIT REACHED: YOU SHALL NOT PASS!");
        }

        // ... your code
    }
}
```

Development
-----------

[](#development)

### Available Scripts

[](#available-scripts)

CommandDescription`composer test`Run PHPUnit tests`composer phpstan`Run PHPStan static analysis`composer cs-fix`Fix code style with PHP-CS-Fixer`composer cs-check`Check code style (dry-run)`composer rector`Run Rector refactoring`composer rector-dry`Preview Rector changes`composer quality`Run all quality tools (Rector + CS-Fixer)`composer quality-check`Check quality without changesLicense
-------

[](#license)

This project is licensed under the GPL-3.0-or-later License - see the [LICENSE](LICENSE) file for details.

Author
------

[](#author)

**Stefano Perrini** - [spinfo.it](https://www.spinfo.it)

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance87

Actively maintained with recent releases

Popularity25

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity64

Established project with proven stability

 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

Every ~201 days

Recently: every ~301 days

Total

7

Last Release

65d ago

PHP version history (2 changes)v1.0.0PHP &gt;=8.1

v1.0.4PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/160662d52c89da3351e2a94b3d354074bf30137477fc7586eeacc52e3cb44462?d=identicon)[snipershady](/maintainers/snipershady)

---

Top Contributors

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

---

Tags

banratelimitratelimiter

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/snipershady-ratelimiter/health.svg)

```
[![Health](https://phpackages.com/badges/snipershady-ratelimiter/health.svg)](https://phpackages.com/packages/snipershady-ratelimiter)
```

###  Alternatives

[cybercog/laravel-ban

Laravel Ban simplify blocking and banning Eloquent models.

1.1k637.7k11](/packages/cybercog-laravel-ban)[mchev/banhammer

Banhammer for Laravel allows you to ban any Model by key and by IP.

36288.0k2](/packages/mchev-banhammer)[hamburgscleanest/guzzle-advanced-throttle

A Guzzle middleware that can throttle requests according to (multiple) defined rules. It is also possible to define a caching strategy, e.g. get response from cache when rate limit is exceeded or always get cached value to spare your rate limits.

13033.4k1](/packages/hamburgscleanest-guzzle-advanced-throttle)[sunspikes/php-ratelimiter

A framework agnostic rate limiter for PHP

76667.7k1](/packages/sunspikes-php-ratelimiter)[cybercog/laravel-nova-ban

A Laravel Nova banning functionality for your application.

42198.1k](/packages/cybercog-laravel-nova-ban)[ethercreative/yii2-ip-ratelimiter

Allow guest clients to be rate limited, using their IP as the identifier.

36136.0k1](/packages/ethercreative-yii2-ip-ratelimiter)

PHPackages © 2026

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