Component that facilitates rate-limiting functionality. Although designed as a standalone, it also provides a middleware designed for API and/or other application endpoints that be used with any framework that supports the middleware concept.
The preferred method of installation is via Composer. Run the following
command to install the latest version of a package and add it to your project's composer.json
:
composer require nikolaposa/rate-limit
$rateLimiter = \RateLimit\RateLimiterFactory::createInMemoryRateLimiter(1000, 3600);
echo $rateLimiter->getLimit(); //1000
echo $rateLimiter->getWindow(); //3600
$rateLimiter->hit('key');
echo $rateLimiter->getRemainingAttempts('key'); //999
echo $rateLimiter->getResetAt('key'); //1486503558
Note: in-memory rate limiter should only be used for testing purposes. This package also provides Redis-backed rate limiter:
$rateLimiter = \RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([
'host' => '10.0.0.7',
'port' => 6379,
], 1000, 3600);
Zend Expressive example:
$app = \Zend\Expressive\AppFactory::create();
$app->pipe(\RateLimit\Middleware\RateLimitMiddleware::createDefault(
\RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([
'host' => '10.0.0.7',
'port' => 6379,
], 1000, 3600)
));
Slim example:
$app = new \Slim\App();
$app->add(\RateLimit\Middleware\RateLimitMiddleware::createDefault(
\RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([
'host' => '10.0.0.7',
'port' => 6379,
], 1000, 3600)
));
Whitelisting requests:
use Psr\Http\Message\RequestInterface;
$rateLimitMiddleware = \RateLimit\Middleware\RateLimitMiddleware::createDefault(
\RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([
'host' => '10.0.0.7',
'port' => 6379,
], 1000, 3600),
[
'whitelist' => function (RequestInterface $request) {
if (false !== strpos($request->getUri()->getPath(), 'admin')) {
return true;
}
return false;
},
]
);
Custom limit exceeded handler:
use Psr\Http\Message\RequestInterface;
use Zend\Diactoros\Response\JsonResponse;
$rateLimitMiddleware = \RateLimit\Middleware\RateLimitMiddleware::createDefault(
\RateLimit\RateLimiterFactory::createRedisBackedRateLimiter([
'host' => '10.0.0.7',
'port' => 6379,
], 1000, 3600),
[
'limitExceededHandler' => function (RequestInterface $request) {
return new JsonResponse([
'message' => 'API rate limit exceeded',
], 429);
},
]
);
Nikola Poša
Copyright 2017 Nikola Poša. Released under MIT License - see the LICENSE
file for details.