touhonoob / rate-limit
PHP rate limiting library with Token Bucket Algorithm
Installs: 417 486
Dependents: 2
Suggesters: 0
Security: 0
Stars: 136
Watchers: 5
Forks: 28
Open Issues: 5
Requires
- php: >=5.6
Requires (Dev)
- php: >7.0
- friendsofphp/php-cs-fixer: ^2.7
- jakub-onderka/php-parallel-lint: ^1.0
- phpunit/phpunit: ^6.0
- predis/predis: ^1.1
- psr/cache: ^1.0
- tedivm/stash: ^0.14
- vimeo/psalm: *
Suggests
- ext-apc: ^4.0
- ext-apcu: ^4.0
- ext-redis: ^2.2
- predis/predis: ^1.1
- tedivm/stash: ^0.14
This package is auto-updated.
Last update: 2024-12-13 17:06:07 UTC
README
PHP Rate Limiting Library With Token Bucket Algorithm with minimal external dependencies.
Installation
composer require palepurple/rate-limit
Storage Adapters
The RateLimiter needs to know where to get/set data.
Depending on which adapter you install, you may need to install additional libraries (predis/predis or tedivm/stash) or PHP extensions (e.g. Redis, Memcache, APC)
- APCu
- Redis or Predis
- Stash (This supports many drivers - see http://www.stashphp.com/Drivers.html )
- Memcached
Example
require 'vendor/autoload.php'; use \PalePurple\RateLimit\RateLimit; use \PalePurple\RateLimit\Adapter\APC as APCAdapter; use \PalePurple\RateLimit\Adapter\Redis as RedisAdapter; use \PalePurple\RateLimit\Adapter\Predis as PredisAdapter; use \PalePurple\RateLimit\Adapter\Memcached as MemcachedAdapter; use \PalePurple\RateLimit\Adapter\Stash as StashAdapter; $adapter = new APCAdapter(); // Use APC as Storage // Alternatives: // // $adapter = new RedisAdapter((new \Redis()->connect('localhost'))); // Use Redis as Storage // // $adapter = new PredisAdapter((new \Predis\Predis())->connect('localhost')); // Use Predis as Storage // // $memcache = new \Memcached(); // $memcache->addServer('localhost', 11211); // $adapter = new MemcacheAdapter($memcache); // // $stash = new \Stash\Pool(new \Stash\Driver\FileSystem()); // $adapter = new StashAdapter($stash); $rateLimit = new RateLimit("myratelimit", 100, 3600, $adapter); // 100 Requests / Hour $id = $_SERVER['REMOTE_ADDR']; // Use client IP as identity if ($rateLimit->check($id)) { echo "passed"; } else { echo "rate limit exceeded"; }
Installing via Composer
curl -sS https://getcomposer.org/installer | php
composer.phar require palepurple/rate-limit