网络环境异常复杂,有时候我们不得不禁止一些恶意用户访问,禁止的方式有很多种,其中一种就是通过 IP 来限制,本文提供的方法允许你通过 IP 区间、CIDR (Classless Inter-Domain Routing)及单个 IP 格式来检查或过滤 IP 地址
你可以通过增加一个配置文件,然后将需要禁止的一些 IP 地址通过一定规则添加到配置文件中,在程序初始化的时候,读取配置文件中的每个规则,然后通过本文提供的方法去检查当前访问的客户端 IP 地址是否存在于这些规则中,如果存在,则拒绝提供服务。
代码如下:
/**
* PHP 中检查或过滤 IP 地址
*
* 支持 IP 区间、CIDR(Classless Inter-Domain Routing)及单个 IP 格式
* 整理:http://www.CodeBit.cn
* 参考:
* - {@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 网段,支持 IP 区间、CIDR及单个 IP 格式
* @param string $ip 要检查的 IP 地址
* @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 // CIDR : 174.129.0.0/16
} else if (false !== strpos($network,"/")) {
list ($net, $mask) = explode ('/', $network);
$result = (ip2long($ip) & ~((1 // 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
?>
由于中国使用的大多数都是动态 IP 地址,所以通过 IP 地址限制访问具有一定的局限性,使用的时候需要谨慎,但是对于应急限制访问来说,还是非常有用的。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version
