首页  >  文章  >  后端开发  >  php如何根据IP地址获取所在城市

php如何根据IP地址获取所在城市

小云云
小云云原创
2018-03-19 15:09:044968浏览

本文主要和大家分享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