stulen 2020-09-15
本文实例为大家分享了php判断IP地址是否在多个IP段内的具体代码,供大家参考,具体内容如下
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='/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地址、地址以及将提交按钮置为不可用状态 } ?>
<?php. if (!empty($_POST)) {. $data1 = $_POST["data1"];$data2 = $_POST["data2"];$fuhao = $_POST["fuh