trukes/php-rate-limiter

A lightweight, flexible rate-limiting library for PHP. Manage access limits by user, IP, or custom keys with support for sliding and fixed windows. Compatible with Redis, MySQL, and file-based storage. Ideal for controlling API usage and preventing abuse.

v1.0.1 2025-01-29 23:44 UTC

This package is auto-updated.

Last update: 2025-01-29 23:47:46 UTC


README

Latest Version on Packagist Total Downloads GitHub Actions

PhpRateLimiter is a simple and flexible rate-limiting library for PHP. It allows you to manage access limits based on custom keys (such as users, IPs, etc.) and can be easily integrated with any injectable storage backend (e.g., Redis, MySQL, etc.). It supports both fixed and sliding time windows. Ideal for controlling API usage and preventing abuse.

Installation

You can install the package via composer:

composer require trukes/php-rate-limiter

Usage

use Trukes\PhpRateLimiter\PhpRateLimiter;
use Psr\SimpleCache\CacheInterface;
use Trukes\PhpRateLimiter\Support\Config;
use Trukes\PhpRateLimiter\Exception\LimitExceededException;

// Example with a PSR-16 compatible cache implementation
$cache = // Your cache implementation (e.g., Redis, file-based cache, etc.)
$config = new Config();

// Instantiate the rate limiter
$rateLimiter = new PhpRateLimiter($cache, $config);

$key = 'user_123'; // Custom key (e.g., user ID, IP, etc.)

try {
    $rateLimiter->hit($key); // Increment the hit count
} catch (LimitExceededException $e) {
    echo 'Limit exceeded: ' . $e->getMessage();
}

// Reset the counter for a key
$rateLimiter->reset($key);

Configuration

You are able to provider configurations to fit your needs:

new Config(
    prefix: 'your-prefix',
    maxRequestsByTimeframe: 10,
    timeframeInSeconds: 1
);

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email pedro.m.a.carmo@gmail.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

PHP Package Boilerplate

This package was generated using the PHP Package Boilerplate by Beyond Code.