PHP code example of twinh / rate-limiter

1. Go to this page and download the library: Download twinh/rate-limiter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

twinh / rate-limiter example snippets


use RateLimiter\FixedWindow;
use RateLimiter\FixedWindow\MemoryStorage;

$limiter = new FixedWindow(new MemoryStorage(), windowSize: 10, limit: 1);
if (!$limiter->attempt('user_id')) {
    echo 'Too many requests';
}

use RateLimiter\FixedWindow;
use RateLimiter\FixedWindow\MemoryStorage;

$limiter = new FixedWindow(new MemoryStorage(), windowSize: 60, limit: 1);

use RateLimiter\SlidingWindow;
use RateLimiter\SlidingWindow\MemoryStorage;

$limiter = new SlidingWindow(new MemoryStorage(), windowSize: 60, limit: 1);

use RateLimiter\LeakyBucket;
use RateLimiter\LeakyBucket\MemoryStorage;

$limiter = new LeakyBucket(new LeakyMemoryStorage(), rate: 10, limit: 1);

use RateLimiter\FixedWindow;
use RateLimiter\FixedWindow\RedisStorage;

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$limiter = new FixedWindow(new RedisStorage($redis), windowSize: 10, limit: 1);

if (!$limiter->attempt('user_id')) {
    echo 'Too many requests';
}

$limiter->attempt();

$limiter->attempt($_SERVER['REMOTE_ADDR'] ?? 'unknown');

$limiter->attempt($_SERVER['SERVER_ADDR'] ?? 'unknown');

$remaining = $limiter->getRemaining('user_id');

$limiter->clear('user_id');