我正在尝试使用 ip/mask 范围读取文件,如果提供的 IP 与文件中的任何范围匹配,它将返回 TRUE 或类似函数。这是我下面的代码
function myip2long($ip) {
if (is_numeric($ip)) {
return sprintf("%u", floatval($ip));
} else {
return sprintf("%u", floatval(ip2long($ip)));
}
}
function ipfilter($ip) {
$match = 0;
$ip_addr = decbin(myip2long($ip));
if (file_get_contents('./countryip/all-zones/us.zone')) {
$source = file('./countryip/all-zones/us.zone');
foreach ($source as $line) {
$network = explode("/", $line);
$net_addr = decbin(myip2long($network[0]));
$cidr = $network[1];
if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
$match = 1;
break;
}
}
}
return $match;
}
$user_ip = $_SERVER['REMOTE_ADDR'];
if (ipfilter($user_ip) == 1) echo "<br />allowed! Your IP is a United States IP!";
else echo "deny!";
示例文件(如上例中的文件)可在此处获得 http://www.ipdeny.com/ipblocks/data/countries/us.zone
不确定上面的代码是否正确,我是从这里得到的' http://www.php.net/manual/en/function.ip2long.php#86793