PHP 根据IP地址获取所在城市

发布时间:2017-09-23 18:17:08编辑:丝画阁阅读(798)

  1. <?php  
  2. header('Content-Type:text/html;Charset=utf-8');  
  3. function GetIp(){  
  4.     $realip = '';  
  5.     $unknown = 'unknown';  
  6.     if (isset($_SERVER)){  
  7.         if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){  
  8.             $arr = explode(','$_SERVER['HTTP_X_FORWARDED_FOR']);  
  9.             foreach($arr as $ip){  
  10.                 $ip = trim($ip);  
  11.                 if ($ip != 'unknown'){  
  12.                     $realip = $ip;  
  13.                     break;  
  14.                 }  
  15.             }  
  16.         }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){  
  17.             $realip = $_SERVER['HTTP_CLIENT_IP'];  
  18.         }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){  
  19.             $realip = $_SERVER['REMOTE_ADDR'];  
  20.         }else{  
  21.             $realip = $unknown;  
  22.         }  
  23.     }else{  
  24.         if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){  
  25.             $realip = getenv("HTTP_X_FORWARDED_FOR");  
  26.         }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){  
  27.             $realip = getenv("HTTP_CLIENT_IP");  
  28.         }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){  
  29.             $realip = getenv("REMOTE_ADDR");  
  30.         }else{  
  31.             $realip = $unknown;  
  32.         }  
  33.     }  
  34.     $realip = preg_match("/[\d\.]{7,15}/"$realip$matches) ? $matches[0] : $unknown;  
  35.     return $realip;  
  36. }  
  37.   
  38. function GetIpLookup($ip = ''){  
  39.     if(empty($ip)){  
  40.         $ip = GetIp();  
  41.     }  
  42.     $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);  
  43.     if(empty($res)){ return false; }  
  44.     $jsonMatches = array();  
  45.     preg_match('#\{.+?\}#'$res$jsonMatches);  
  46.     if(!isset($jsonMatches[0])){ return false; }  
  47.     $json = json_decode($jsonMatches[0], true);  
  48.     if(isset($json['ret']) && $json['ret'] == 1){  
  49.         $json['ip'] = $ip;  
  50.         unset($json['ret']);  
  51.     }else{  
  52.         return false;  
  53.     }  
  54.     return $json;  
  55. }  
  56.   
  57.   
  58. $ipInfos = GetIpLookup('123.125.114.144'); //baidu.com IP地址  
  59. var_dump($ipInfos); 

关键字