PHP checks or filters out the implementation code of IP addresses. You can add some IP addresses that need to be disabled to the configuration file by adding a configuration file with certain rules. during program initialization, to read each IP address in the configuration file, you can add a configuration file and add some IP addresses that need to be disabled to the configuration file through certain rules. during program initialization, read each rule in the configuration file, and then use the method provided in this article to check whether the IP address of the currently accessed client exists in these rules. If yes, the service is denied.
The code is as follows:
/**
* Check or filter IP addresses in PHP
*
* Supports IP ranges, CIDR (Classless Inter-Domain Routing), and a single IP address format.
* Finishing: 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 segment, which supports IP ranges, CIDR, and a single IP address format
* @ Param string $ ip address of the IP address to be checked
* @ 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 <(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 ', '192. 129.1.31'); // True
Var_dump (netMatch ('174.129.0.0/16', '192. 139.1.31 '); // False
Var_dump (netMatch ('174.129.1.32 ', '192. 129.1.31'); // False
?>
Because most of the IP addresses in China are dynamic IP addresses, it has some limitations to restrict access through IP addresses. exercise caution when using these IP addresses. However, it is very useful to restrict access in emergency scenarios.
The IP address is added to the configuration file through certain rules. during program initialization, each of...