Back to the module list

Rate-limiter with file backend

The rate limit forbid return false if there is too much called to the "set" methods in a time period.

It need to store the data in a file by identifier. By default, the data/ratelimit/ directory is used, but it can be changed in $storageDir.

By default, the rate-limiter is configured for 10 calls in 60 seconds, but it can be configured by $maxEntries and $unittime properties.

In the following example, the identifier is error-$ipClient.

$ratelimiter = new Domframework\Ratelimitfile ();
/** The maximum number of entries by specified unit time */
$ratelimiter->maxEntries = 10;
/** The unit time in seconds */
$ratelimiter->unittime = 60;
$ipClient = null;
if (isset ($_SERVER["HTTP_X_FORWARDED_FOR"]))
  $ipClient = $_SERVER["HTTP_X_FORWARDED_FOR"];
elseif (isset ($_SERVER["REMOTE_ADDR"]))
  $ipClient = $_SERVER["REMOTE_ADDR"];
$ratelimiter->set ("error-$ipClient") === false)
{
 throw new \Exception ("Too much error requests", 406);
}
echo "Below the rate-limit threshold\n";

If needed, the programmer can drop the ratelimiter entries for a specific identifier by using the "del" method.

The "clean" method remove the unused identifier if they are too old.

The class definition

Class Domframework\Ratelimitfile

Namespace Domframework

Description

/**
 The rate limit with file storage

Properties

public $debug=false;
/**
 Debug the ratelimiting process to screen
public $maxEntries=10;
/**
 The maximum number of entries by specified unit time
public $storageDir="data/ratelimit/";
/**
 The storage directory
public $unittime=60;
/**
 The unit time in seconds

Methods

public function clean ()
/**
 The function clean the storage with expired entries
 @return bool

public function del ( $name)
/**
 The function delete a rate-limit
 @param string $name The rate-limit object to del
 @return bool

public function set ( $name)
/**
 The function set a rate-limit
 @param string $name The rate-limit object to set
 @return bool true if the rate-limit is not overloaded
              false if the rate-limit is overloaded