PHPackages                             anjola/php\_rate\_limiter - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. anjola/php\_rate\_limiter

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

anjola/php\_rate\_limiter
=========================

A PHP Library that seamlessly integrate limiting into your platform, supports Redis ,FileSystem , Datbases such as SQL Relational Database.

1.0.0(1y ago)11Apache-2.0PHP

Since May 22Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/Anjolaanuoluwapo101/php-rate-limiter)[ Packagist](https://packagist.org/packages/anjola/php_rate_limiter)[ RSS](/packages/anjola-php-rate-limiter/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (8)Versions (2)Used By (0)

PHP Rate Limiter
================

[](#php-rate-limiter)

A PHP Library that seamlessly integrates rate limiting into your platform. It supports multiple storage backends including Redis, File System, and SQL Relational Databases, providing flexible and efficient request limiting capabilities.

---

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

[](#table-of-contents)

- [Introduction](#introduction)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
    - [RateLimiter](#ratelimiter)
    - [Analytics](#analytics)
- [Storage Options](#storage-options)
- [Examples](#examples)
- [License](#license)
- [Author](#author)

---

Introduction
------------

[](#introduction)

The PHP Rate Limiter library provides a simple and extensible way to limit the number of requests or actions a user or system can perform within a specified time window. It supports multiple storage backends to suit different environments and scales, including Redis, file-based storage, SQL databases, and session storage.

Additionally, the library includes an Analytics component to track custom events, allowing you to monitor usage patterns or other metrics alongside rate limiting.

---

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

[](#installation)

You can install the library via Composer:

```
composer require anjola/php_rate_limiter
```

### Requirements

[](#requirements)

- PHP 7.2.5 or higher
- Extensions:
    - `fileinfo`
- Dependencies:
    - `vlucas/phpdotenv` for environment variable management
    - `predis/predis` for Redis support

---

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

[](#configuration)

The library uses environment variables to configure storage options. You can create a `.env` file in your project root to set these variables.

### Important Environment Variables

[](#important-environment-variables)

VariableDescriptionDefault`STORAGE_DRIVER`Storage backend to use (`redis`, `file`, `database`, `session`)`sqlite` (file-based)`ANALYTICS_STORAGE_FILE_NAME`File name for analytics storage when using file driver`analytics_storage.json``RATELIMITER_STORAGE_FILE_NAME`File name for rate limiter storage when using file driver`ratelimiter_storage.json`Make sure to configure your environment according to your preferred storage backend.

---

Usage
-----

[](#usage)

### RateLimiter

[](#ratelimiter)

The `RateLimiter` class allows you to limit the number of attempts for a given key within a decay period.

#### Initialization

[](#initialization)

```
use PHPRateLimiter\RateLimiter;

$maxAttempts = 5;      // Maximum allowed attempts
$decaySeconds = 60;    // Time window in seconds

$rateLimiter = new RateLimiter($maxAttempts, $decaySeconds);
```

#### Check if too many attempts

[](#check-if-too-many-attempts)

```
$key = 'user_ip_or_identifier';

if ($rateLimiter->tooManyAttempts($key)) {
    // Handle rate limit exceeded (e.g., block request, show error)
} else {
    // Proceed with the request
}
```

#### Clear records for a key

[](#clear-records-for-a-key)

```
$rateLimiter->clearRecords($key);
```

---

### Analytics

[](#analytics)

The `Analytics` class allows you to track custom events and retrieve their counts.

#### Initialization

[](#initialization-1)

```
use PHPRateLimiter\Analytics;

$prefix = 'myapp_';  // Optional prefix for event keys
$analytics = new Analytics($prefix);
```

#### Track an event

[](#track-an-event)

```
$event = 'homepage_visit';
$count = $analytics->trackEvent($event);
echo "Event count: " . $count;
```

#### Get event count

[](#get-event-count)

```
$count = $analytics->getEventCount($event);
```

#### Reset event count

[](#reset-event-count)

```
$analytics->resetEvent($event);
```

---

Storage Options
---------------

[](#storage-options)

The library supports multiple storage backends to store rate limiting and analytics data. You can configure the storage driver via the `STORAGE_DRIVER` environment variable.

### Supported Drivers

[](#supported-drivers)

- **Redis** (default)

    - Requires Redis server and `predis/predis` package.
    - High performance and suitable for distributed environments.
- **File System**

    - Stores data in JSON files.
    - Configurable file names via environment variables.
    - Suitable for simple or local setups.
- **Database**

    - Supports SQL relational databases.
    - Requires appropriate database setup and configuration.
- **Session**

    - Uses PHP session storage.
    - Suitable for per-session rate limiting.

### Configuration Example

[](#configuration-example)

Set the storage driver in your `.env` file:

```
STORAGE_DRIVER=redis
```

Or for file storage:

```
STORAGE_DRIVER=file
RATELIMITER_STORAGE_FILE_NAME=ratelimiter_storage.json
ANALYTICS_STORAGE_FILE_NAME=analytics_storage.json
```

---

Examples
--------

[](#examples)

### Basic Rate Limiting Example

[](#basic-rate-limiting-example)

```
require 'vendor/autoload.php';

use PHPRateLimiter\RateLimiter;

$rateLimiter = new RateLimiter(10, 60); // 10 attempts per 60 seconds
$key = $_SERVER['REMOTE_ADDR'];

if ($rateLimiter->tooManyAttempts($key)) {
    header('HTTP/1.1 429 Too Many Requests');
    echo "You have exceeded the maximum number of requests. Please try again later.";
    exit;
}

// Proceed with your application logic here
```

### Analytics Tracking Example

[](#analytics-tracking-example)

```
require 'vendor/autoload.php';

use PHPRateLimiter\Analytics;

$analytics = new Analytics('app_');
$analytics->trackEvent('user_signup');

echo "User signup count: " . $analytics->getEventCount('user_signup');
```

---

License
-------

[](#license)

This project is licensed under the Apache-2.0 License. See the [LICENSE](LICENSE) file for details.

---

Author
------

[](#author)

**Anjolaanuoluwapo**
Email:

---

Thank you for using PHP Rate Limiter! If you have any questions or issues, feel free to open an issue or contact the author.

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance60

Regular maintenance activity

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 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

408d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/111210173?v=4)[Akinsoyinu Anjola Anuoluwapo](/maintainers/Anjolaanuoluwapo101)[@Anjolaanuoluwapo101](https://github.com/Anjolaanuoluwapo101)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/anjola-php-rate-limiter/health.svg)

```
[![Health](https://phpackages.com/badges/anjola-php-rate-limiter/health.svg)](https://phpackages.com/packages/anjola-php-rate-limiter)
```

###  Alternatives

[blair2004/nexopos

The Free Modern Point Of Sale System build with Laravel, TailwindCSS and Vue.js.

1.2k2.4k](/packages/blair2004-nexopos)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[lullabot/drainpipe

An automated build tool to allow projects to have a set standardized operations scripts.

43785.5k4](/packages/lullabot-drainpipe)[lion/bundle

Lion-framework configuration and initialization package

122.3k4](/packages/lion-bundle)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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