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.
You can install the package via composer:
composer require trukes/php-rate-limiter
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);
You are able to provider configurations to fit your needs:
new Config(
prefix: 'your-prefix',
maxRequestsByTimeframe: 10,
timeframeInSeconds: 1
);
composer test
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
This package was generated using the PHP Package Boilerplate by Beyond Code.