Home  >  Article  >  php教程  >  php ip获取与判断IP分段类

php ip获取与判断IP分段类

WBOY
WBOYOriginal
2016-06-08 17:29:081293browse

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;
 }
}

Statement:
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