PHP code example of sndsgd / rate

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

    

sndsgd / rate example snippets


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