PHP獲取ip與ip所在城市


1獲取真實ip,本地測試總是::1 或者127.0.0.1 或者局域網的ip

/**
 * 獲取用戶真實 IP
 */
function getIP()
{
    static $realip;
    if (isset($_SERVER)){
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    return $realip;
}
 

 2.根據ip獲取地址

/**
 * 獲取 IP  地理位置
 * 淘寶IP接口
 * @Return: array
 */
function getCity($ip = '')
{
    if($ip == ''){
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
        $ip=json_decode(file_get_contents($url),true);
        $data = $ip;
    }else{
        $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
        $ip=json_decode(file_get_contents($url));   
        if((string)$ip->code=='1'){
           return false;
        }
        $data = (array)$ip->data;
    }
    
    return $data;   
}

測試

var_dump(getIP());
var_dump(getCity());
var_dump(getCity('218.93.250.162'));

結果

string(3) "::1"
array(10) {
  ["ret"]=>
  int(1)
  ["start"]=>
  int(-1)
  ["end"]=>
  int(-1)
  ["country"]=>
  string(6) "中國"
  ["province"]=>
  string(6) "江蘇"
  ["city"]=>
  string(6) "宿遷"
  ["district"]=>
  string(0) ""
  ["isp"]=>
  string(0) ""
  ["type"]=>
  string(0) ""
  ["desc"]=>
  string(0) ""
}
array(13) {
  ["country"]=>
  string(6) "中國"
  ["country_id"]=>
  string(2) "CN"
  ["area"]=>
  string(6) "華東"
  ["area_id"]=>
  string(6) "300000"
  ["region"]=>
  string(9) "江蘇省"
  ["region_id"]=>
  string(6) "320000"
  ["city"]=>
  string(9) "宿遷市"
  ["city_id"]=>
  string(6) "321300"
  ["county"]=>
  string(0) ""
  ["county_id"]=>
  string(2) "-1"
  ["isp"]=>
  string(6) "電信"
  ["isp_id"]=>
  string(6) "100017"
  ["ip"]=>
  string(14) "218.93.250.162"
}

說明:新浪的接口,直接能獲取到地址信息,淘寶的接口需要提供ip,不過獲取的信息更全面


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM