Read more: https://csspan.com/2013/02/02/php-request-throttling/ Demo: https://www.vileworks.com/projects/limit.php
Last active
January 17, 2024 03:49
-
-
Save nonsalant/dd56ac00e4b8b82c9317 to your computer and use it in GitHub Desktop.
Throttling requests on a per IP basis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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