Skip to content

Instantly share code, notes, and snippets.

@levelsio
Created April 24, 2019 08:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save levelsio/fa519aea897e8f0fb441ddaf555eb3e0 to your computer and use it in GitHub Desktop.
Save levelsio/fa519aea897e8f0fb441ddaf555eb3e0 to your computer and use it in GitHub Desktop.
MAKE book IP limiter (req'd by @rashidi_life)
#
// check if customer hash correct
loadDbs(array('customers'));
$query=$customersDb->prepare("SELECT * FROM customers WHERE secret_hash=:secret_hash");
$query->bindValue(':secret_hash',$_GET['hash']);
$query->execute();
$customers=$query->fetchAll(PDO::FETCH_ASSOC);
$customer=$customers[0];
if(!empty($customer) && $customers[0]['secret_hash']==$_GET['hash']) {
$userPaidForBook=true;
$customer=$customers[0];
}
else {
echo "Can't find hash, sorry!";
$_COOKIE['hash']='';
unset($_COOKIE);
unset($_SESSION);
exit;
}
if($customers[0]['ip_addresses']!=='allow_infinite') {
if(!empty($customers[0]['ip_addresses'])) {
$ips=explode("\n",$customers[0]['ip_addresses']);
$maxIps=4;
if(count($ips)>$maxIps) {
list($epoch,$ip)=explode("\t",$ips[0]);
$ip=trim($ip);
// if oldest (first) IP usage was within 24 hours, it means there's $maxIps IPs that used it within last 24h, so we lock
// otherwise remove the oldest IP, and add the new one
if($epoch>strtotime("-24 hours")) {
echo "Too many different IPs have accessed this book, to protect file sharing, the book is locked. Try again later!";
echo '<hr><pre>';
foreach($ips as $ip_line) {
list($epoch,$ip)=explode("\t",$ip_line);
echo date('c',$epoch);
echo "\t";
echo $ip;
echo "\n";
}
exit;
}
}
$newIps=array();
foreach($ips as $ip_line) {
list($epoch,$ip)=explode("\t",$ip_line);
$ip=trim($ip);
if($ip!=$_SERVER['REMOTE_ADDR']) {
array_push($newIps,$ip_line);
}
}
if(count($newIps)>$maxIps) {
// pop first element off IPs
array_shift($newIps);
}
$ips=$newIps;
}
else {
$ips=array();
}
array_push($ips,time()."\t".$_SERVER['REMOTE_ADDR']);
$ip_addresses_string='';
foreach($ips as $ip_line) {
$ip_addresses_string=$ip_addresses_string.$ip_line."\n";
}
// remove \n last
$ip_addresses_string=substr($ip_addresses_string,0,strlen($ip_addresses_string)-1);
// save new IP to db
$query=$customersDb->prepare("UPDATE customers SET ip_addresses=:ip_addresses WHERE secret_hash=:secret_hash");
$query->bindValue(':secret_hash',$_GET['hash']);
$query->bindValue(':ip_addresses',$ip_addresses_string);
$query->execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment