PHP code example of beheh / flaps

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

    

beheh / flaps example snippets


use Predis\Client;
use BehEh\Flaps\Storage\PredisStorage;
use BehEh\Flaps\Flaps;
use BehEh\Flaps\Throttling\LeakyBucketStrategy;

// setup with Redis as storage backend
$storage = new PredisStorage(new Client());
$flaps = new Flaps($storage);

// allow 3 requests per 5 seconds
$flaps->login->pushThrottlingStrategy(new LeakyBucketStrategy(3, '5s'));
//or $flaps->__get('login')->pushThrottlingStrategy(...)

// limit by ip (default: send "HTTP/1.1 429 Too Many Requests" and die() on violation)
$flaps->login->limit($_SERVER['REMOTE_ADDR']);

use BehEh\Flaps\Throttling\LeakyBucketStrategy;
use BehEh\Flaps\Violation\PassiveViolationHandler;

$flap = $flaps->__get('api');
$flap->pushThrottlingStrategy(new LeakyBucketStrategy(15, '10s'));
$flap->setViolationHandler(new PassiveViolationHandler);
if (!$flap->limit(filter_var(INPUT_GET, 'api_key'))) {
	die(json_encode(array('error' => 'too many requests')));
}

use BehEh\Flaps\Throttling\LeakyBucketStrategy;

$flap = $flaps->__get('add_comment');
$flap->pushThrottlingStrategy(new LeakyBucketStrategy(1, '30s'));
$flap->pushThrottlingStrategy(new LeakyBucketStrategy(10, '10m'));
$flap->limit($userid);

use Predis\Client;
use BehEh\Flaps\Storage\PredisStorage;
use BehEh\Flaps\Flaps;

$storage = new PredisStorage(new Client('tcp://10.0.0.1:6379'));
$flaps = new Flaps($storage);

use Doctrine\Common\Cache\ApcCache;
use BehEh\Flaps\Storage\DoctrineCacheAdapter;
use BehEh\Flaps\Flaps;

$apc = new ApcCache();
$apc->setNamespace('MyApplication');
$storage = new DoctrineCacheAdapter($apc);
$flaps = new Flaps($storage);

use BehEh\Flaps\Throttle\LeakyBucketStrategy;

$flap->pushThrottlingStrategy(new LeakyBucketStrategy(60, '10m'));

use BehEh\Flaps\Violation\HttpViolationHandler;

$flap->setViolationHandler(new HttpViolationHandler);
$flap->limit($identifier);  // send "HTTP/1.1 429 Too Many Requests" and die() on violation

use BehEh\Flaps\Violation\PassiveViolationHandler;

$flap->setViolationHandler(new PassiveViolationHandler);
if (!$flap->limit($identifier)) {
	// violation
}

use BehEh\Flaps\Violation\ExceptionViolationHandler;
use BehEh\Flaps\Violation\ThrottlingViolationException;

$flap->setViolationHandler(new ExceptionViolationHandler);
try {
	$flap->limit($identifier); // throws ThrottlingViolationException on violation
}
catch (ThrottlingViolationException $e) {
	// violation
}

$flaps->setDefaultViolationHandler(new CustomViolationHandler);

$flap = $flaps->__get('login');
$flap->addThrottlingStrategy(new TimeBasedThrottlingStrategy(1, '1s'));
$flap->limit($identifier); // will use CustomViolationHandler