|
本帖最后由 Dead⌒leaves 于 2014-6-27 21:59 编辑
首先:我们来使用一个经常见到的函数getip()来实现IP的获取:
function getip(){
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
{ $ip = getenv("HTTP_CLIENT_IP");
} else if (
getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
{ $ip = getenv("HTTP_X_FORWARDED_FOR");
} else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
{ $ip = getenv("REMOTE_ADDR");
} else if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
{ $ip = $_SERVER['REMOTE_ADDR']; } else { $ip = "unknown"; } return $ip;
}
第二步:将获取到的IP地址传递个新浪IP接口,
利用一个常用的函数file_get_contents来获取其json格式的返回值,这样我们就可以实现IP地址与对应省份城市的转换;
function getLocation($ip='')
{ empty($ip) && $ip = getip();
if($ip=="127.0.0.1") return "本机地址"; $api = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json& ip=$ip"; $json = @file_get_contents($api);//调用新浪IP地址库
$arr = json_decode($json,true);//解析json $country = $arr['country']; //取得国家
$province = $arr['province'];//获取省份 $city = $arr['city']; //取得城市
if((string)$country == "中国"){ if((string)($province) != (string)$city){ $_location = $province.$city; }else{ $_location = $country.$city; } }else{ $_location = $country; } return $_location;}
第三步:功能的实现
echo getLocation(); //或者 echo getLocation("222.210.4.66");
|
|