PHP code example of jdimitrov / php-ratelimit

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

    

jdimitrov / php-ratelimit example snippets

composer 

$adapter = new RedisAdapter((new \Redis()->connect('localhost'))); // Use Redis as Storage

// Alternatives:
//
// $adapter = new PredisAdapter(new \Predis\Predis(['tcp://127.0.0.1:6379'])); // Use Predis as Storage
//
// $memcache = new \Memcached();
// $memcache->addServer('localhost', 11211);
// $adapter = new MemcacheAdapter($memcache); 
//
// $adapter = new APCAdapter(); // Use APC as Storage

$key = 'ratelimit';
// $key = 'ratelimit' . ':' .  $_SERVER['REMOTE_ADDR']; // You can append identificator, if you want to narrow your limits to specific ip address or to something else

$rate_limit = new RateLimit($key, 100, 1, $adapter); // 100 requests per second

if ($rate_limit->check(30)) { // Try to consume 30 requests
    // Success
} else {
    // Failed (leaked bucket)
}