1. 程式人生 > 程式設計 >php判斷IP地址是否在多個IP段內

php判斷IP地址是否在多個IP段內

本文例項為大家分享了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地址、地址以及將提交按鈕置為不可用狀態
}
 
?>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。