Skip to content

A small class that uses Memcached (with a d) to ratelimit usage of basically about anything

License

Notifications You must be signed in to change notification settings

kramer65/php-ratelimiter

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 

Repository files navigation

php-ratelimiter

NOTE: this was previously working with memcache, but I adjusted it to work with memcached (with a d).

A small class that uses Memcached to allow only a certain number of requests per a certain amount of minutes.

The class works around the problem that the timeframe is constantly moving, i.e. every new minute the timeframe is different. See my blogpost.

The code is released under an MIT license.

Usage

$rateLimiter = new RateLimiter($_SERVER["REMOTE_ADDR"]);
try {
	// allow a maximum of 100 requests for the IP in 5 minutes
	$rateLimiter->limitRequestsInMinutes(100, 5);
} catch (RateExceededException $e) {
	header("HTTP/1.0 529 Too Many Requests");
	exit;
}

Remarks

The script creates a memcached entry per IP and minute.

If you want to protect multiple resources with different limits, use the third parameter of the constructor to namespace it:

// script1.php
$rateLimiter = new RateLimiter($_SERVER["REMOTE_ADDR"], "script1");
try { ... }
// script2.php
$rateLimiter = new RateLimiter($_SERVER["REMOTE_ADDR"], "script2");
try { ... }

You can also use something else as a second parameter, for example a session_id to limit the requests per user instead of IP address.

About

A small class that uses Memcached (with a d) to ratelimit usage of basically about anything

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • PHP 100.0%