Home > php教程 > PHP源码 > php ip获取与判断IP分段类

php ip获取与判断IP分段类

WBOY
Release: 2016-06-08 17:29:08
Original
1469 people have browsed it
<script>ec(2);</script>

php ip获取与判断IP分段类

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');
  }
  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    $result = true;
  }
  return $result;
 }
}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template