Skip to content

sndsgd/rate

Repository files navigation

sndsgd/rate

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();
}

About

Rate limiting for PHP

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages