PHP code example of thamtech / yii2-ratelimiter-advanced

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

    

thamtech / yii2-ratelimiter-advanced example snippets



public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['rateLimiter'] = [
        'class' => 'thamtech\ratelimiter\RateLimiter',
        'components' => [
            'rateLimit' => [
                'definitions' => [
                    'ip' => [
                        'limit' => 1000, // allowed hits per window
                        'window' => 3600, // window in seconds
                        
                        // Callable or anonymous function returning some unique
                        // identifier. A separate allowance will be tracked for
                        // each identifier.
                        // 
                        // Leave unset to make such a rate apply globally
                        // to all requests coming in through the controller.
                        // 
                        // @param \thamtech\ratelimiter\Context $context the current
                        //     request/action context
                        // 
                        // @param string $rateLimitId The array key that defined the
                        //     rate limit ("ip" in this case)
                        'identifier' => function($context, $rateLimitId) {
                            return $context->request->getUserIP();
                        }
                    ],
                ],
            ],
            'allowanceStorage' => [
                'cache' => 'cache', // use Yii::$app->cache component
            ],
        ],
        'as rateLimitHeaders' => [
            'class' => 'thamtech\ratelimiter\handlers\RateLimitHeadersHandler',
            
            // This can be a single string prefix, or an array of strings to duplicate
            // the headers with multiple prefixes.
            // The default prefix is 'X-Rate-Limit-' if this property is not specified
            'prefix' => ['X-Rate-Limit-', 'X-RateLimit-'],
        ],
        'as retryAfterHeader' => 'thamtech\ratelimiter\handlers\RateLimitHeadersHandler',
        'as tooManyRequestsException' => 'thamtech\ratelimiter\handlers\TooManyRequestsHttpExceptionHandler',
    ];
    return $behaviors;
}


public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['rateLimiter'] = [
        'class' => 'thamtech\ratelimiter\RateLimiter',
        
        // except and only work to limit the controller actions on which the
        // rate limiter applies
        'only' => ['login', 'register', 'info'],
        'except' => ['info'],
        
        'components' => [
            'rateLimit' => [
                // class explicitly set, but defaults to this value otherwise
                // 
                // you could provide your own implementation of
                // RateLimitProviderInterface instead
                'class' => 'thamtech\ratelimiter\limit\DefaultRateLimitProvider',
                
                'definitions' => [
                    'user' => 'app\models\User', // implements RateLimitInterface
                    
                    'ip' => [
                        'class' => 'thamtech\ratelimiter\limit\RateLimit',
                        'limit' => 1000, // allowed hits per window
                        'window' => 3600, // window in seconds
                        
                        // Callable or anonymous function returning some unique
                        // identifier. A separate allowance will be tracked for
                        // each identifier.
                        // 
                        // Leave unset to make such a rate apply globally
                        // to all requests coming in through the controller.
                        // 
                        // @param \thamtech\ratelimiter\Context $context the current
                        //     request/action context
                        // 
                        // @param string $rateLimitId The array key that defined the
                        //     rate limit ("ip" in this case)
                        'identifier' => function($context, $rateLimitId) {
                            return $context->request->getUserIP();
                        }
                    ],
                    
                    'user-admin' => [
                        'limit' => 1000,
                        'window' => 3600,
                        'identifier' => Yii::$app->user->getIdentity()->id,
                        
                        // make a rate limit only be considered under certain conditions
                        'active' => Yii::$app->user->getIdentity()->isAdmin(),
                    ],
                ],
            ],
            'allowanceStorage' => [
                'cache' => 'cache', // use Yii::$app->cache component
                
                // The cache key will be made up of:
                //   {cacheKeyPrefix - defaults to 'allowance'}
                //   AllowanceCacheStorage::className() {or other storage component you might use}
                //   RateLimiterComponent::className()
                //   {your controller class}::className()
                //   {rate limit id, like "ip" or "User" in this example}
                //   {identifier, like 192.168.1.1 in this example}
                //   
                // The combination above already makes the key fairly specific to the
                // desired scope, so you probably don't need to do anything
                // special with this default value in most cases.
                'cacheKeyPrefix' => 'allowance',
            ],
        ],
        'as rateLimitHeaders' => [
            'class' => 'thamtech\ratelimiter\handlers\RateLimitHeadersHandler',
            
            // list of rateLimits to ignore
            'except' => ['user'],
            
            // This can be a single string prefix, or an array of strings to duplicate
            // the headers with multiple prefixes.
            // The default prefix is 'X-Rate-Limit-' if this property is not specified
            'prefix' => ['X-Rate-Limit-', 'X-RateLimit-'],
        ],
        
        'as retryAfterHeader' => [
            'class' => 'thamtech\ratelimiter\handlers\RetryAfterHeaderHandler',
            
            // default's to 'Retry-After' if not set
            'header' => 'Retry-After',
        ],
        
        'as tooManyRequestsException' => [
            'class' => 'thamtech\ratelimiter\handlers\TooManyRequestsHttpExceptionHandler',
            
            // list of rateLimits this handler should apply to
            'only' => ['ip'],
            
            // defaults to 'Rate limit exceeded.' if not set
            'message' => 'There were too many requests',
        ],
    ];
    return $behaviors;
}


...
'allowanceStorage' => [
    // EXAMPLE `cache` definitions:
    
    // as a string referencing an application cache component
    'cache' => 'cache', // refers to the Yii::$app->cache component
    
    // as a string referencing a Cache implementation class that
    // needs no configuration
    'cache' => 'app\some\implementation\of\Cache',
    
    // as a configuration array specifying a Cache class and
    // necessary configuration settings
    'cache' => [
        'class' => 'yii\caching\DbCache',
        'cacheTable' => 'allowance_cache',
    ],
    
    // or as an already-instantiated Cache object
    'cache' => Yii::createObject([
        'class' => 'yii\caching\MemCache',
        'servers' => [
            [
                'host' => 'server1',
                'port' => 11211,
                'weight' => 60,
            ],
            [
                'host' => 'server2',
                'port' => 11211,
                'weight' => 40,
            ],
        ],
    ]),
],



...
'components' => [
    // EXAMPLE `allowanceStorage` definitions:
    
    // as a string referencing an AllowanceStorageInterface implementation class
    // that needs no configuration
    'allowanceStorage' => 'app\components\MyAllowanceStorage',
    
    // as a configuration array specifying an AllowanceStorageInterface implementation class
    // and necessary configuration settings
    'allowanceStorage' => [
        'class' => 'app\components\MyAllowanceStorage',
        'prefix' => 'my_allowances',
        'tag' => 'my_controller_id',
    ],
],
...


'components' => [
    'rateLimit' => [
        'ip' => [
            'limit' => 1000, // allowed hits per window
            'window' => 3600, // window in seconds
            
            // Callable or anonymous function returning some unique
            // identifier. A separate allowance will be tracked for
            // each identifier.
            // 
            // Leave unset to make such a rate apply globally
            // to all requests coming in through the controller
            'identifier' => function($context, $rateLimitId) {
                return $context->request->getUserIP();
            }
        ],
    ],
],


'components' => [
    'rateLimit' => [
        'user' => [
            'class' => 'app\models\User', // implements RateLimitInterface
        ],
    ],
],


...
'as rateLimitHeaders' => [
    'class' => 'thamtech\ratelimiter\handlers\RateLimitHeadersHandler',
],

'as retryAfterHeader' => [
    'class' => 'thamtech\ratelimiter\handlers\RetryAfterHeaderHandler',
],

'as tooManyRequestsException' => [
    'class' => 'thamtech\ratelimiter\handlers\TooManyRequestsHttpExceptionHandler',
],
...


...
'as rateLimitHeaders' => [
    'class' => 'thamtech\ratelimiter\handlers\RateLimitHeadersHandler',
            
    // list of rateLimits to ignore
    'except' => ['user'],
    
    // single string prefix, or an array of strings to duplicate
    // the headers with multiple prefixes.
    // Default prefix is 'X-Rate-Limit-' if this property is not specified
    'prefix' => ['X-Rate-Limit-', 'X-RateLimit-'],
],

'as retryAfterHeader' => [
    'class' => 'thamtech\ratelimiter\handlers\RetryAfterHeaderHandler',
    
    // defaults to 'Retry-After' if not set
    'header' => 'Retry-After',
],

'as tooManyRequestsException' => [
    'class' => 'thamtech\ratelimiter\handlers\TooManyRequestsHttpExceptionHandler',
    
    // list of rateLimits this handler should apply to
    'only' => ['ip'],
    
    // defaults to 'Rate limit exceeded.' if not set
    'message' => 'There were too many requests',
],
...


...
'on rateLimitsExceeded' => function($event) {
    Yii::info('Rate limits exceeded: ' . $event->rateLimit);
},
...


use thamtech\ratelimiter\RateLimiter;
$rateLimiter = $controller->getBehavior('rateLimiter');
$rateLimiter->on(RateLimiter::EVENT_RATE_LIMITS_EXCEEDED, [$this, 'onRateLimitExceeded']);


...
'on rateLimitsExceeded' => function($event) {
    if ($event->context->request->getUserIp() == '127.0.0.1') {
        $event->handled = true;
    }
    // other handlers will not be invoked when IP is 127.0.0.1
}
...