Skip to content

Instantly share code, notes, and snippets.

@nonsalant
Last active January 17, 2024 03:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nonsalant/dd56ac00e4b8b82c9317 to your computer and use it in GitHub Desktop.
Save nonsalant/dd56ac00e4b8b82c9317 to your computer and use it in GitHub Desktop.
Throttling requests on a per IP basis
<?php
// https://vileworks.com/projects/limit.php
// This page can only be accessed 5 times in any 10 second interval.
function limit_requests($nr=5,$t=10) {
if (!session_id()) {
start_session_based_on_ip();
}
if( !isset($_SESSION['tzero']) ) {
$_SESSION['tzero']=time();
}
$since_interval_start = time() - $_SESSION['tzero'];
if( $since_interval_start> $t ) {
$_SESSION['tzero'] = time();
$_SESSION['hits'] = 1;
} else {
$_SESSION['hits']++;
}
if( $_SESSION['hits'] > $nr ) {
die('<h1>Too many requests!</h1> You will be able to make a new request in <b style="color:red">'.($t-$since_interval_start).'</b> seconds.');
}
$remaining_hits = $nr - $_SESSION['hits'];
$remaining_time = $t - $since_interval_start;
if ( $remaining_time < 0 ) $remaining_time = $t;
}
function start_session_based_on_ip() {
$ip_hash = md5($_SERVER['REMOTE_ADDR']);
session_id($ip_hash);
session_start();
}
limit_requests();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment