Home > Backend Development > PHP Tutorial > Implementation code for checking or filtering IP addresses in PHP_PHP tutorial

Implementation code for checking or filtering IP addresses in PHP_PHP tutorial

WBOY
Release: 2016-07-21 15:22:20
Original
908 people have browsed it

You can add a configuration file, and then add some IP addresses that need to be banned to the configuration file through certain rules. When the program is initialized, read each rule in the configuration file, and then use the method provided in this article to check the current Whether the accessed client IP address exists in these rules, if so, the service is denied.

Copy code The code is as follows:

/**
* Check or filter IP addresses in PHP
*
* Support IP range, CIDR (Classless Inter-Domain Routing) and single IP format
* Organized by: 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 network segment, supports IP range, CIDR and single IP format
* @param string $ip IP address to check
* @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 IP addresses used in China are dynamic IP addresses, restricting access through IP address has certain limitations. You need to be careful when using it, but it is still very useful for emergency access restriction.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324737.htmlTechArticleYou can add a configuration file and then add some IP addresses that need to be banned to the configuration file through certain rules. , when the program is initialized, read each configuration file...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template