PHP ratelimiter

Overview

php-ratelimiter

A small class that uses Memcache 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

limitRequestsInMinutes(100, 5); } catch (RateExceededException $e) { header("HTTP/1.0 529 Too Many Requests"); exit; }">
$rateLimiter = new RateLimiter(new Memcache(), $_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(new Memcache(), $_SERVER["REMOTE_ADDR"], "script1");
try { ... }
// script2.php
$rateLimiter = new RateLimiter(new Memcache(), $_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.

You might also like...
PHP exercises from my course at ETEC and some of my own play-around with PHP

etec-php-exercises PHP exercises from my course at ETEC and some of my own play-around with PHP Translations: Português (BR) Projects Project Descript

GitHub action to set up PHP with extensions, php.ini configuration, coverage drivers, and various tools.
GitHub action to set up PHP with extensions, php.ini configuration, coverage drivers, and various tools.

GitHub action to set up PHP with extensions, php.ini configuration, coverage drivers, and various tools.

php-echarts is a php library for the echarts 5.0.

php-echarts 一款支持Apache EChart5.0+图表的php开发库 优先ThinkPHP5/6的开发及测试。 Apache EChart5.0已经最新发布,在视觉效果、动画效果和大数据展示方面已经远超之前的版本; 故不考虑EChart5.0之前版本的兼容问题;建议直接尝试5.0+

Minimalist PHP frame for Core-Library, for Developing PHP application that gives you the full control of your application.

LazyPHP lightweight Pre-Made Frame for Core-library Install Run the below command in your terminal $ composer create-project ryzen/lazyphp my-first-pr

Zilliqa PHP is a typed PHP-7.1+ interface to Zilliqa JSON-RPC API.
Zilliqa PHP is a typed PHP-7.1+ interface to Zilliqa JSON-RPC API.

Zilliqa PHP is a typed PHP-7.1+ interface to Zilliqa JSON-RPC API. Check out the latest API documentation. Add library in a composer.json file.

churn-php is a package that helps you identify php files in your project that could be good candidates for refactoring
churn-php is a package that helps you identify php files in your project that could be good candidates for refactoring

churn-php Helps discover good candidates for refactoring. Table of Contents What Is it? Compatibility How to Install? How to Use? How to Configure? Si

Run your WP site on github pages, php innovation award winner  https://www.phpclasses.org/package/12091-PHP-Make-a-WordPress-site-run-on-GitHub-pages.html
Run your WP site on github pages, php innovation award winner https://www.phpclasses.org/package/12091-PHP-Make-a-WordPress-site-run-on-GitHub-pages.html

Gitpress Run wordpress directly on github pages Gitpress won the innovation award for may 2021 Read more about this https://naveen17797.github.io/gitp

A pure PHP implementation of the MessagePack serialization format / msgpack.org[PHP]

msgpack.php A pure PHP implementation of the MessagePack serialization format. Features Fully compliant with the latest MessagePack specification, inc

SublimeLinter 3 plugin for PHP, using php -l.

SublimeLinter-php This linter plugin for SublimeLinter provides an interface to php -l. It will be used with files that have the "PHP", "HTML", or "HT

Comments
  • No servers added to memcache connection ERROR

    No servers added to memcache connection ERROR

    I'm having problems when trying to run the script

    Warning: Memcache::get(): No servers added to memcache connection in /public_html/path/to/script.php on line 45

    problem comes from this: $this->memcache->set($key, 1, 0, $minutes * 60 + 1);

    any thoughts on how to fix that?

    opened by thagxt 2
  • Adjusted for memcached

    Adjusted for memcached

    Hallo Alexander,

    For our own usage I adjusted this to work with memcached instead of memcache. If you're open to this you can merge. If you would rather keep it with memcache that's fine as well. In that case you might link to my version for people interested in the memcached version.

    Whatever you do, have a beautiful day!

    opened by kramer65 0
  • Call the rate limiter many times in the same php code with different limits

    Call the rate limiter many times in the same php code with different limits

    With this branch we can do this:

    $memcache = new Memcache;
    $memcache->connect('127.0.0.1',11211);
    
    $rateLimiter = new RateLimiter($memcache, $_SERVER["REMOTE_ADDR"]);
    try {
        // 10 requests / minute
        $rateLimiter->limitRequestsInMinutes(10, 1);
    } catch (RateExceededException $e) {
        header("HTTP/1.0 529 Too Many Requests");
        exit;
    }
    
    try {
        // 30 requests / 5 minute
        $rateLimiter->limitRequestsInMinutes(30, 5);
    } catch (RateExceededException $e) {
        header("HTTP/1.0 529 Too Many Requests");
        exit;
    }
    

    etc....

    opened by leonardoxc 0
A sampling profiler for PHP written in PHP, which reads information about running PHP VM from outside of the process.

Reli Reli is a sampling profiler (or a VM state inspector) written in PHP. It can read information about running PHP script from outside of the proces

null 272 Dec 22, 2022
PHP Meminfo is a PHP extension that gives you insights on the PHP memory content

MEMINFO PHP Meminfo is a PHP extension that gives you insights on the PHP memory content. Its main goal is to help you understand memory leaks: by loo

Benoit Jacquemont 994 Dec 29, 2022
A sampling profiler for PHP written in PHP, which reads information about running PHP VM from outside of the process.

Reli Reli is a sampling profiler (or a VM state inspector) written in PHP. It can read information about running PHP script from outside of the proces

null 258 Sep 15, 2022
A multithreaded application server for PHP, written in PHP.

appserver.io, a PHP application server This is the main repository for the appserver.io project. What is appserver.io appserver.io is a multithreaded

appserver.io 951 Dec 25, 2022
Easy to use utility functions for everyday PHP projects. This is a port of the Lodash JS library to PHP

Lodash-PHP Lodash-PHP is a port of the Lodash JS library to PHP. It is a set of easy to use utility functions for everyday PHP projects. Lodash-PHP tr

Lodash PHP 474 Dec 31, 2022
A PHP 5.3+ and PHP 7.3 framework for OpenGraph Protocol

Opengraph Test with Atoum cd Opengraph/ curl -s https://getcomposer.org/installer | php php composer.phar install --dev ./vendor/atoum/atoum/bin/atoum

Axel Etcheverry 89 Dec 27, 2022
A status monitor for Elite Dangerous, written in PHP. Designed for 1080p screens in the four-panel-view in panel.php, and for 7 inch screens with a resolution of 1024x600 connected to a Raspberry Pi.

EDStatusPanel A status monitor for Elite Dangerous, written in PHP. Designed for 1080p screens in the four-panel-view in panel.php, and for 7 inch scr

marcus-s 24 Oct 4, 2022
🐘 A probe program for PHP environment (一款精美的 PHP 探針, 又名X探針、劉海探針)

Simplified Chinese | 简体中文 Traditional Chinese(Taiwan) | 正體中文(臺灣) Traditional Chinese(Hong Kong) | 正體中文(香港) Japanese | 日本語 ?? X Prober This is a probe

Km.Van 1.2k Dec 28, 2022
PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP language

php-text-analysis PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP l

null 464 Dec 28, 2022
PHP generics written in PHP

PHP generics written in PHP Require PHP >= 7.4 Composer (PSR-4 Autoload) Table of contents How it works Quick start Example Features Tests How it work

Anton Sukhachev 173 Dec 30, 2022