samescolas / rate-limit
General purpose rate limiter implementation.
2.2.0
2021-01-14 09:38 UTC
Requires
- php: ^7.2 || ^8.0
- beberlei/assert: ^3.2
Requires (Dev)
- ext-apcu: >=5.1.12
- ext-redis: *
- friendsofphp/php-cs-fixer: ^2.17
- phpstan/phpstan: ^0.12.10
- phpstan/phpstan-beberlei-assert: ^0.12.2
- phpstan/phpstan-phpunit: ^0.12.6
- phpunit/phpunit: ^8.0
- predis/predis: ^1.1
Suggests
- ext-apcu: In order to use ApcuRateLimiter
- ext-memcached: In order to use MemcachedRateLimiter
- ext-redis: In order to use RedisRateLimiter
- predis/predis: In order to use PredisRateLimiter
This package is not auto-updated.
Last update: 2025-05-07 14:32:03 UTC
README
General purpose rate limiter that can be used to limit the rate at which certain operation can be performed. Default implementation uses Redis as backend.
Installation
The preferred method of installation is via Composer. Run the following
command to install the latest version of a package and add it to your project's composer.json
:
composer require samescolas/rate-limit
Usage
Offensive rate limiting
use RateLimit\Exception\LimitExceeded; use RateLimit\Rate; use RateLimit\RedisRateLimiter; use Redis; $rateLimiter = new RedisRateLimiter(new Redis()); $apiKey = 'abc123'; try { $rateLimiter->limit($apiKey, Rate::perMinute(100)); //on success } catch (LimitExceeded $exception) { //on limit exceeded }
Silent rate limiting
use RateLimit\Rate; use RateLimit\RedisRateLimiter; use Redis; $rateLimiter = new RedisRateLimiter(new Redis()); $ipAddress = '192.168.1.2'; $status = $rateLimiter->limitSilently($ipAddress, Rate::perMinute(100)); echo $status->getRemainingAttempts(); //99
Credits
License
Released under MIT License - see the License File for details.