PHP code example of andrewdyer / predis-request-limiter

1. Go to this page and download the library: Download andrewdyer/predis-request-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/ */

    

andrewdyer / predis-request-limiter example snippets


use Predis\Client;

$client = new Client([
    'scheme' => 'tcp',
    'host'   => '127.0.0.1',
    'port'   => 6379,
]);

use AndrewDyer\PredisRequestLimiter\Limiter;

$limiter = new Limiter($client, '127.0.0.1');

$limiter->setRateLimit(requests: 10, perSecond: 60);

if ($limiter->hasExceededRateLimit()) {
    // Limit exceeded — respond with 429 or invoke the handler
} else {
    $limiter->incrementRequestCount();
}

$limiter->setLimitExceededHandler(function (): void {
    http_response_code(429);
    echo 'Too many requests.';
    exit;
});

if ($limiter->hasExceededRateLimit()) {
    ($limiter->getLimitExceededHandler())();
} else {
    $limiter->incrementRequestCount();
}

$limiter->setStorageKey('api:limit:%s');