The implementation code in PHP that checks or filters the IP address

  • 2020-05-10 17:48:42
  • OfStack

You can add 1 through a configuration file, and then will need to ban some IP 1 address by 1 set rules added to the configuration file, at the time of initialization program, each rule in the configuration file is read, and then through the provided method to check whether the current access client IP address exists in these rules, if present, declined to provide services.
 
<?php 
/** 
* PHP  Check or filter  IP  address  
* 
*  support  IP  Interval, CIDR ( Classless Inter-Domain Routing ) and a single  IP  format  
*  Finish: http://www.CodeBit.cn 
*  Reference:  
* - {@link http://us2.php.net/manual/zh/function.ip2long.php#70055} 
* - {@link http://us2.php.net/manual/zh/function.ip2long.php#82397} 
* 
* @param string $network  Net segment, support  IP  Interval, CIDR And a single  IP  format  
* @param string $ip  To check the  IP  address  
* @return boolean 
*/ 
function netMatch($network, $ip) { 
$network = trim($network); 
$ip = trim($ip); 
$result = false; 
// IP range : 174.129.0.0 - 174.129.255.255 
if (false !== ($pos = strpos($network, "-"))) { 
$from = ip2long(trim(substr($network, 0, $pos))); 
$to = ip2long(trim(substr($network, $pos+1))); 
$ip = ip2long($ip); 
$result = ($ip >= $from and $ip <= $to); 
// CIDR : 174.129.0.0/16 
} else if (false !== strpos($network,"/")) { 
list ($net, $mask) = explode ('/', $network); 
$result = (ip2long($ip) & ~((1 << (32 - $mask)) - 1)) == ip2long($net); 
// single IP 
} else { 
$result = $network === $ip; 
} 
return $result; 
} 
// 174.129.0.0 - 174.129.255.255 
var_dump(netMatch(' 174.129.0.0 - 174.129.255.255 ', '174.129.1.31')); // True 
var_dump(netMatch(' 174.129.0.0/16 ', '174.139.1.31')); // False 
var_dump(netMatch(' 174.129.1.32 ', '174.129.1.31')); // False 
?> 

Since most of the addresses used in China are dynamic IP addresses, restricting access through IP addresses has a definite limitation, which requires caution when used, but is still very useful for emergency access restrictions.

Related articles: