PHP code example of robwittman / leaky-bucket-rate-limiter

1. Go to this page and download the library: Download robwittman/leaky-bucket-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/ */

    

robwittman / leaky-bucket-rate-limiter example snippets




eakyBucketRateLimiter\RateLimiter;

$slim = \Slim\App();

$slim->add(new RateLimiter([
    'callback' => function(RequestInterface $request) {
        return [
            'token' => <token>
        ];
    },
    'throttle' => function(ResponseInterface $response) {
        return $response->withStatus(429)->withJson([
            'error' => "User request limit reached"
        ]);
    }
]))

$slim->run();

$slim->add(new RateLimiter([
    'callback' => function(RequestInterface $request) {
        return [
            'token' => $_SERVER['REMOTE_ADDR']
        ];
    }
]));

$slim->add(new RateLimiter([
    'callback' => function(RequestInterface $request) {
        return [
            'token' => session_id()
        ];
    }
]));

$slim->add(new RateLimiter([
    'capacity' => 45,
    'leak' => 1
]));

$slim->add(new RateLimiter([
    'header' => "Rate-Limiting-Meta"
]));

// Rate-Limiting-Meta: X / Y
// X = Current drips in bucket, Y = capacity
 php
$slim->add(new RateLimiter([
    'callback' => function(RequestInterface $request) {
        return [
            'token' => $request->getAttribute('<token_or_uid>')
        ];
    },
]));

 php
$slim->add(new RateLimiter([
    'callback' => function(RequestInterface $request) {
        return [
            'token' => session_id()
        ];
    }
]))
 php
$slim->add(new RateLimiter([
    'throttle' => function(ResponseInterface $response) {
        return $response->withStatus(429)->withJson([
            'message' => "Dude, you gotta slow down"
        ]);
    };
]));
 php
$slim->add(new RateLimiter([
    'ignore' => [
        'auth/token',
        'users/me',
        'other/ignored/routes'
    ]
]));
 php
$slim->add(new RateLimiter([
    // Rate limiter settings
], [
    'scheme' => 'tcp://',
    'host' => 'redis',
    'port' => 6379
]))

// OR

class ObjectWithGetAndSetMethods {
    public function get($key) {
        return $this->{$key};
    }
    public function set($key, $value) {
        $this->{$key} = $value;
    }
}
$storage = new ObjectWithGetAndSetMethods();
$slim->add(new RateLimiter([
    // Rate limiter settings
], $storage));