php判斷IP地址是否在多個IP段內
阿新 • • 發佈:2019-02-04
IP.class.php
<?php class Ip { /** * 取IP * @return string */ public static function get() { if ($_SERVER['HTTP_CLIENT_IP'] && $_SERVER['HTTP_CLIENT_IP']!='unknown') { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif ($_SERVER['HTTP_X_FORWARDED_FOR'] && $_SERVER['HTTP_X_FORWARDED_FOR']!='unknown') { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } /** * IP轉成整形數值 * @param string $ip IP * @return int */ public static function ipToInt($ip) { $ips = explode('.',$ip); if (count($ips)==4) { $int = $ips[0]*256*256*256+$ips[1]*256*256+$ips[2]*256+$ips[3]; //根據IP,a,b,c類進行計算 } else { //throw new Exception('ip is error'); Tool::Alert('IP地址存在錯誤...'); //一個工具類,彈出提示資訊 } return $int; } /** * 判斷IP是否在一個IP段內 * @param string $startIp 開始IP * @param string $endIp 結束IP * @param string $ip IP * @return bool */ public static function isIn($startIp, $endIp, $ip) { $start = Ip::ipToInt($startIp); $end = Ip::ipToInt($endIp); $ipInt = Ip::ipToInt($ip); $result = false; if ($ipInt>=$start && $ipInt<=$end) { $result = true; } return $result; } } ?>
IpRang.class.php
<?php
//將不同的IP段儲存到陣列中..
$iprang=array(
array('222.243.159.1','222.243.159.255'),
array('10.1.1.1','10.1.1.255')
);
?>
test.php<?php require_once 'Tool.class.php'; //工具類 require_once 'IP.class.php'; //IP類 require_once 'IpRang.class.php'; //IP段範圍 $ip = IP::get(); //獲取IP地址 $tag='1'; foreach($iprang as $key => $value){ if(!IP::isIn($value[0], $value[1], $ip)){ continue; }else{ $tag.=$key; } } if(mb_strlen($tag,'utf-8')==1){ echo "<script src='http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=".$ip."' type='text/javascript'></script>";//呼叫新浪IP介面 echo "<script type='text/javascript'>alert('很遺憾,您所用的裝置網路不在某某範圍內...\\n".$ip."\\n'+remote_ip_info.province+remote_ip_info.city+remote_ip_info.district); $(\"input[name='submit']\").attr(\"disabled\",true);</script>"; //彈出提示框,顯示IP地址、地址以及將提交按鈕置為不可用狀態 } ?>