1. header('Content-Type:text/html;Charset=utf-8');  

  2. function GetIp(){  

  3.     $realip = '';  

  4.     $unknown = 'unknown';  

  5.     if (isset($_SERVER)){  

  6.         if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){  

  7.             $arr = explode(','$_SERVER['HTTP_X_FORWARDED_FOR']);  

  8.             foreach($arr as $ip){  

  9.                 $ip = trim($ip);  

  10.                 if ($ip != 'unknown'){  

  11.                     $realip = $ip;  

  12.                     break;  

  13.                 }  

  14.             }  

  15.         }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){  

  16.             $realip = $_SERVER['HTTP_CLIENT_IP'];  

  17.         }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){  

  18.             $realip = $_SERVER['REMOTE_ADDR'];  

  19.         }else{  

  20.             $realip = $unknown;  

  21.         }  

  22.     }else{  

  23.         if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){  

  24.             $realip = getenv("HTTP_X_FORWARDED_FOR");  

  25.         }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){  

  26.             $realip = getenv("HTTP_CLIENT_IP");  

  27.         }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){  

  28.             $realip = getenv("REMOTE_ADDR");  

  29.         }else{  

  30.             $realip = $unknown;  

  31.         }  

  32.     }  

  33.     $realip = preg_match("/[\d\.]{7,15}/"$realip$matches) ? $matches[0] : $unknown;  

  34.     return $realip;  

  35. }  

  36.   

  37. function GetIpLookup($ip = ''){  

  38.     if(empty($ip)){  

  39.         $ip = GetIp();  

  40.     }  

  41.     $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);  

  42.     if(empty($res)){ return false; }  

  43.     $jsonMatches = array();  

  44.     preg_match('#\{.+?\}#'$res$jsonMatches);  

  45.     if(!isset($jsonMatches[0])){ return false; }  

  46.     $json = json_decode($jsonMatches[0], true);  

  47.     if(isset($json['ret']) && $json['ret'] == 1){  

  48.         $json['ip'] = $ip;  

  49.         unset($json['ret']);  

  50.     }else{  

  51.         return false;  

  52.     }  

  53.     return $json;  

  54. }  

  55.   

  56.   

  57. $ipInfos = GetIpLookup('123.125.114.144'); //baidu.com IP地址  

  58. var_dump($ipInfos);  


结果截图:

PHP 根据IP地址获取所在城市_第1张图片


使用了新浪的开放API,执行速度还是非常赞的。

本文来自于 CSDN,转载请标注出处!http://blog.csdn.net/liruxing1715/article/details/28238483