PHP to check or filter IP address implementation code _php tips

Source: Internet
Author: User
Tags manual
You can add a configuration file, then add some IP addresses that need to be banned through a set of rules to the configuration file, read each rule in the configuration file when the program is initialized, and then check to see if the current access client IP address exists in these rules, if one exists, by using the method provided in this article. Refuses to provide the service.
Copy Code code as follows:

<?php
/**
* Check or filter IP address in PHP
*
* Support IP interval, CIDR (classless Inter-Domain Routing) and single IP 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 network segment, support IP interval, CIDR and single IP format
* @param string $IP The 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
?>

Because most of the Chinese are dynamic IP addresses, restricting access through IP addresses has some limitations and requires caution when used, but is also useful for emergency restricted access.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.