sndsgd/rate

Rate limiting for PHP

0.1.2 2016-12-24 19:39 UTC

This package is not auto-updated.

Last update: 2024-11-23 20:21:08 UTC


README

Latest Version Software License Build Status Coverage Status Total Downloads

Rate limiting for PHP.

Requirements

This project is unstable and subject to changes from release to release.

You need PHP >= 7.0 to use this library, however, the latest stable version of PHP is recommended.

Install

Install sndsgd/rate using Composer.

Usage

Note: At the moment, this library only contains rate limiting tools.

# define the rate limits
$clientIp = $di->getClient()->getIp();
$limits = [
    new \sndsgd\rate\Limit("Search-PerSecond", $clientIp, 1, 3),
    new \sndsgd\rate\Limit("Search-PerHour", $clientIp, 600, 3600),
];

# create a limiter, and increment the hit counts for all limits
$redis = $di->getRedis();
$limiter = new \sndsgd\rate\limiter\RedisLimiter($redis, $limits);
$limiter->increment();

# copy the rate limit headers to the response
$response = $di->getResponse();
foreach ($limiter->getHeaders() as $header) {
    list($key, $value) = preg_split("/\:\s?/", $header, 2);
    $response->addHeader($key, $value);
}

# if the limit was exceeded, prevent futher execution
if ($limiter->isExceeded()) {
    throw new \sndsgd\http\exception\TooManyRequestsException();
}