PHP code example of yiisoft / rate-limiter

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

    

yiisoft / rate-limiter example snippets


use Psr\Http\Message\ServerRequestInterface;
use Yiisoft\Yii\RateLimiter\LimitRequestsMiddleware;
use Yiisoft\Yii\RateLimiter\Counter;
use Nyholm\Psr7\Factory\Psr17Factory;
use Yiisoft\Yii\RateLimiter\Policy\LimitAlways;
use Yiisoft\Yii\RateLimiter\Policy\LimitPerIp;
use Yiisoft\Yii\RateLimiter\Policy\LimitCallback;
use Yiisoft\Yii\RateLimiter\Storage\StorageInterface;
use Yiisoft\Yii\RateLimiter\Storage\SimpleCacheStorage;

/** @var StorageInterface $storage */
$storage = new SimpleCacheStorage($cache);

$counter = new Counter($storage, 2, 5);
$responseFactory = new Psr17Factory();

$middleware = new LimitRequestsMiddleware($counter, $responseFactory); // LimitPerIp by default

$middleware = new LimitRequestsMiddleware($counter, $responseFactory, new LimitPerIp());
// or
$middleware = new LimitRequestsMiddleware($counter, $responseFactory, new LimitAlways());

$middleware = new LimitRequestsMiddleware($counter, $responseFactory, new LimitCallback(function (ServerRequestInterface $request): string {
    // return user id from database if authentication id used i.e. limit guests and each authenticated user separately.
}));