PHP code example of mata-sh / rate-limiter

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

    

mata-sh / rate-limiter example snippets


use MataSh\RateLimiter\RateLimitIdentifier;
use MataSh\RateLimiter\RateLimiter;
use MataSh\RateLimiter\Storage\FileStorage;

$limiter = new RateLimiter(new FileStorage('/var/app/cache/rate-limit'));
$identifier = RateLimitIdentifier::fromIp();
$result = $limiter->consume($identifier, 100, 3600);

if (!$result->isAllowed()) {
    $retryAt = $result->getRetryAt();
    // Reject the request. $retryAt is the Unix timestamp when one request can next succeed.
}

if (!$limiter->allow($identifier, 100, 3600)) {
    // Reject the request.
}

$status = $limiter->check($identifier, 100, 3600);

if (!$status['allowed']) {
    // Reject the request without adding a request to the window.
}

$limiter->reset($identifier);

$removed = $limiter->cleanup(100); // Removes at most 100 expired records.

$limiter->setRateLimitingConfig(120, 60);

$limiter->allow($identifier); // Uses 120 requests / 60 seconds.
$limiter->check($identifier); // Uses the same defaults.

$limiter->setRateLimitingEnabled(false);

$enabled = $limiter->isRateLimitingEnabled();
$maxRequests = $limiter->getDefaultMaxRequests();
$windowSeconds = $limiter->getDefaultWindow();
$storage = $limiter->getStorage();

use Psr\Log\LoggerInterface;

/** @var LoggerInterface $logger */
$limiter = new RateLimiter(
    new FileStorage('/var/app/cache/rate-limit'),
    $logger,
);

use MataSh\RateLimiter\Storage\FileStorage;

$storage = new FileStorage('/var/app/cache/rate-limit');
$limiter = new RateLimiter($storage);

$removed = $limiter->cleanup(100); // Removes at most 100 expired files.

use MataSh\RateLimiter\Storage\ApcuStorage;

$limiter = new RateLimiter(new ApcuStorage());

use MataSh\RateLimiter\Storage\RedisStorage;

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

$limiter = new RateLimiter(new RedisStorage($redis));

use MataSh\RateLimiter\RateLimitIdentifier;

RateLimitIdentifier::getClientIp();
RateLimitIdentifier::fromIp();
RateLimitIdentifier::fromIpUser($username);
RateLimitIdentifier::fromApiKey($apiKey);
RateLimitIdentifier::fromUserId($userId);
RateLimitIdentifier::fromResource($resourceId);
RateLimitIdentifier::custom($identifier);