jdimitrov/php-ratelimit

PHP rate limiting library with Leaky Bucket Algorithm

Installs: 71

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 1

Forks: 0

Open Issues: 0

pkg:composer/jdimitrov/php-ratelimit

0.3 2021-12-07 22:21 UTC

This package is auto-updated.

Last update: 2025-12-08 06:53:31 UTC


README

PHP Rate Limiting Library With Leaky Bucket Algorithm with minimal external dependencies.

Installation

composer require jdimitrov/php-ratelimit

Storage Adapters

The PHP Rate Limit needs to know where to store data.

Depending on which adapter you install, you may need to install additional libraries (predis/predis) or PHP extensions (e.g. Redis, Memcached, APC)

Example

Add uses:

use JDimitrov\RateLimit\RateLimit;
use JDimitrov\RateLimit\Adapter\APC as APCAdapter;
use JDimitrov\RateLimit\Adapter\Redis as RedisAdapter;
use JDimitrov\RateLimit\Adapter\Predis as PredisAdapter;
use JDimitrov\RateLimit\Adapter\Memcached as MemcachedAdapter;
$adapter = new RedisAdapter((new \Redis()->connect('localhost'))); // Use Redis as Storage

// Alternatives:
//
// $adapter = new PredisAdapter(new \Predis\Predis(['tcp://127.0.0.1:6379'])); // Use Predis as Storage
//
// $memcache = new \Memcached();
// $memcache->addServer('localhost', 11211);
// $adapter = new MemcacheAdapter($memcache); 
//
// $adapter = new APCAdapter(); // Use APC as Storage

$key = 'ratelimit';
// $key = 'ratelimit' . ':' .  $_SERVER['REMOTE_ADDR']; // You can append identificator, if you want to narrow your limits to specific ip address or to something else

$rate_limit = new RateLimit($key, 100, 1, $adapter); // 100 requests per second

if ($rate_limit->check(30)) { // Try to consume 30 requests
    // Success
} else {
    // Failed (leaked bucket)
}