PHP code example of fanqingxuan / ratelimiter

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

    

fanqingxuan / ratelimiter example snippets




son\RateLimiter\Cache;
use Json\RateLimiter\RedisStore;
use Json\RateLimiter\MemcacheStore;
use Json\RateLimiter\RateLimiter;

/**
$redis = new Redis;
$redis->connect('127.0.0.1', 6379);

$redisCache = new RedisStore($redis,'lock');
$cache = new Cache($redisCache);

*/

$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211);

$memcacheStore = new MemcacheStore($memcache,'lock');
$cache = new Cache($memcacheStore);

$rateLimter = new RateLimiter($cache);

$key = 'hello';
$maxAttempts = 10;
$seconds = 60;

if($rateLimter->tooManyAttempts("hello",$maxAttempts)) {
	var_dump("can use after ".$rateLimter->availableIn($key).' seconds');
	throw new Exception("over the max attempts");
}

$rateLimter->hit($key, $seconds);

var_dump("left attempt amount:".$rateLimter->retriesLeft($key,$maxAttempts));