php根据ip地址获取所在城市实现代码

发布时间:2020-01-10编辑:脚本学堂
有关php根据ip地址获取所在城市的方法,根据用户ip地址定位用户所在的城市,用到了新浪API接口,获取地理位置信息速度很快。

例子:根据用户IP地址定位用户所在的城市
 

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

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

结果截图:
 

php根据ip地址获取所在城市

使用新浪开放API,执行速度很快。