Ban identifier after certain amount of requests in a given timeframe.
Install composer in your project:
curl -s http://getcomposer.org/installer | php
Create a composer.json file in your project root:
{
"require": {
"websoftwares/throttle": "dev-master"
}
}
Install via composer
php composer.phar install
Basic usage of the Throttle
class to ban an identifier.
use Websoftwares\Throttle, Websoftwares\Storage\Memcached, Monolog\Logger;
// Ip
$identifier = '$_SERVER["REMOTE_ADDR"]';
// Instantiate class
$throttle = new Throttle(new Logger('throttle'), new Memcached());
if($throttle->validate($identifier)) {
// Success proceed
} else {
// Banned
}
Any logger library that implements the PSR-3 LoggerInterface should work,
just create your Logger object and inject it into the Throttle
constructor.
For example the excellent logging library Monolog.
Included is a Memcached
example however it is very easy to use some other storage system
just implement the StorageInterface and inject that object into the Throttle
constructor.
####Caution#### Whatever storage system u decide to use, don not store the failed request data into your database, this could lead to a DDOS attack and take your database down.
U can override the default options by instantiating a Throttle
class and pass in an array as the third argument.
$options = array(
'banned' => 10, // Ban identifier after 10 attempts. (default 5)
'logged' => 20, // Log identifier after 20 attempts. (default 10)
'timespan' => 60 // The timespan for the duration of the ban. (default 86400)
);
// Instantiate class
$throttle = new Throttle(new Logger('throttle'), new Memcached(), $options);
This will remove the identifier from the storage.
$throttle->reset($identifier);
This will return an integer that is the remaining attempt(s) available before identifier gets banned.
$throttle->remaining($identifier);
This requires u have the PHP memcached extension installed.
on Debian/Ubuntu systems for example install like this (requires administrative password).
sudo apt-get install php5-memcached
In the tests folder u can find several tests.
DBAD Public License.
Converted from python example and comments from Forrst.com post.