首頁 >後端開發 >php教程 >php如何根據IP位址取得所在城市

php如何根據IP位址取得所在城市

小云云
小云云原創
2018-03-19 15:09:045023瀏覽

本文主要和大家分享php如何依照IP位址取得所在城市,本文主要以程式碼的形式,希望能幫助大家。

<?php
header(&#39;Content-Type:text/html;Charset=utf-8&#39;);
function GetIp(){
    $realip = &#39;&#39;;
    $unknown = &#39;unknown&#39;;
    if (isset($_SERVER)){
        if(isset($_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;]) && !empty($_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;]) && strcasecmp($_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;], $unknown)){
            $arr = explode(&#39;,&#39;, $_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;]);
            foreach($arr as $ip){
                $ip = trim($ip);
                if ($ip != &#39;unknown&#39;){
                    $realip = $ip;
                    break;
                }
            }
        }else if(isset($_SERVER[&#39;HTTP_CLIENT_IP&#39;]) && !empty($_SERVER[&#39;HTTP_CLIENT_IP&#39;]) && strcasecmp($_SERVER[&#39;HTTP_CLIENT_IP&#39;], $unknown)){
            $realip = $_SERVER[&#39;HTTP_CLIENT_IP&#39;];
        }else if(isset($_SERVER[&#39;REMOTE_ADDR&#39;]) && !empty($_SERVER[&#39;REMOTE_ADDR&#39;]) && strcasecmp($_SERVER[&#39;REMOTE_ADDR&#39;], $unknown)){
            $realip = $_SERVER[&#39;REMOTE_ADDR&#39;];
        }else{
            $realip = $unknown;
        }
    }else{
        if(getenv(&#39;HTTP_X_FORWARDED_FOR&#39;) && strcasecmp(getenv(&#39;HTTP_X_FORWARDED_FOR&#39;), $unknown)){
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        }else if(getenv(&#39;HTTP_CLIENT_IP&#39;) && strcasecmp(getenv(&#39;HTTP_CLIENT_IP&#39;), $unknown)){
            $realip = getenv("HTTP_CLIENT_IP");
        }else if(getenv(&#39;REMOTE_ADDR&#39;) && strcasecmp(getenv(&#39;REMOTE_ADDR&#39;), $unknown)){
            $realip = getenv("REMOTE_ADDR");
        }else{
            $realip = $unknown;
        }
    }
    $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;
    return $realip;
}

function GetIpLookup($ip = &#39;&#39;){
    if(empty($ip)){
        $ip = GetIp();
    }
    $res = @file_get_contents(&#39;http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=&#39; . $ip);
    if(empty($res)){ return false; }
    $jsonMatches = array();
    preg_match(&#39;#\{.+?\}#&#39;, $res, $jsonMatches);
    if(!isset($jsonMatches[0])){ return false; }
    $json = json_decode($jsonMatches[0], true);
    if(isset($json[&#39;ret&#39;]) && $json[&#39;ret&#39;] == 1){
        $json[&#39;ip&#39;] = $ip;
        unset($json[&#39;ret&#39;]);
    }else{
        return false;
    }
    return $json;
}


$ipInfos = GetIpLookup(&#39;123.125.114.144&#39;); //baidu.com IP鍦板潃
var_dump($ipInfos);
?>

相關推薦:

PHP根據IP位址取得所在城市具體實作_PHP教學

#

以上是php如何根據IP位址取得所在城市的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn