Skip to content

A simple and flexible PHP rate-limiting library. Manage access limits with custom keys and any injectable storage backend (e.g., Redis, MySQL). Supports fixed and sliding time windows.

License

Notifications You must be signed in to change notification settings

Trukes/php-rate-limiter

Repository files navigation

Php Rate Limiter

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 [email protected] 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.

About

A simple and flexible PHP rate-limiting library. Manage access limits with custom keys and any injectable storage backend (e.g., Redis, MySQL). Supports fixed and sliding time windows.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Languages