php judge ip blacklist program code instance

  • 2021-01-11 01:54:57
  • OfStack

The news system of the school requires that some news only be accessible to ip, so we rewrote one code to realize this function. The result is that, as long as the permitted ip is listed in the file ip. txt, it also supports ip class c, for example:

ip.txt
192.168
211.67.188
211.67.191.25
The code is as follows:


/*
* ip Address blacklist, whitelist 
*  To judge the address of a visitor ip Whether in ip.txt In the support c class ip
* By xhat
*/
$ip = $_SERVER['REMOTE_ADDR'];
$ipArray = preg_replace("#rn?|n#","",file('ip.txt'));
foreach ($ipArray as $ipTest) {
if (substr_count($ip, $ipTest) != "0") {
echo "ok"; // Execute relevant commands 
die();
}
}
?>

Above we can use the code to cheat, the following code to upgrade


<?php 
class block_ip { 
var $Block_ip = array("192.168.1.1","210.10.2.1-20","222.34.4.*"); 
function __construct(){ 
} 
function __destruct(){ 
} 
private function makePregIP($str){ 
if (strstr($str,"-")) { 
$aIP = explode(".",$str); 
foreach ($aIP as $k=>$v) { 
if (!strstr($v,"-")) { 
$preg_limit .= makePregIP($v); 
} else{ 
$aipNum = explode("-",$v); 
for($i=$aipNum[0];$i<=$aipNum[1];$i++){ 
$preg .=$preg?"|".$i:"[".$i; 
} 
$preg_limit .=strrpos($preg_limit,".",1)==(strlen($preg_limit)-1)?$preg."]":".".$preg."]"; 
} 
} 
}else{ 
$preg_limit .= $str."."; 
} 
return $preg_limit; 
} 
private function getAllBlockIP(){ 
if ($this->Block_ip) { 
foreach ($this->Block_ip as $k=>$v) { 
$ipaddres = $this->makePregIP($v->start_ip); 
$ip = str_ireplace(".",".",$ipaddres); 
$ip = str_replace("*","[0-9]{1,3}",$ip); 
$ipaddres = "/".$ip."/"; 
$ip_list[] = $ipaddres; 
} 
} 
return $ip_list; 
} 
public function checkIP() { 
$iptable = $this->getAllBlockIP(); 
$IsJoined = true; 
// Get the user ip 
$Ip = $this->get_client_ip(); 
$Ip = trim($Ip); 
// Off the blacklist IP section  
if ($iptable) { 
foreach($iptable as $value) { 
if (preg_match("{$value}",$Ip)) { 
$IsJoined = false; 
break; 
} 
} 
} 
//  If the ip The following operations are performed in the blacklist  
if( !$IsJoined ){ 
echo "IP Error"; 
exit; 
} 
} 
private function get_client_ip(){ 
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
$ip = getenv("HTTP_CLIENT_IP"); 
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
$ip = getenv("HTTP_X_FORWARDED_FOR"); 
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
$ip = getenv("REMOTE_ADDR"); 
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
$ip = $_SERVER['REMOTE_ADDR']; 
else 
$ip = "unknown"; 
return($ip); 
} 
} 
?>

Cited excerpts:


$oBlock_ip = new block_ip(); 
$oBlock_ip->checkIP();


Related articles: