在直接在ie浏览器中打开下面地址
http://ip.taobao.com/service/getIpInfo.php?ip=8.8.8.8
返回信息
代码如下 |
复制代码 |
{"code":0,"data":{"country":"u7f8eu56fd","country_id":"US","area":"","area_id":"","region":"","region_id":"","city":"","city_id":"","county":"","county_id":"","isp":"","isp_id":"","ip":"8.8.8.8"}}
|
上面我们是直接在ie地址输入,这里我们利用php file_get_contents函数来获取
代码如下 |
复制代码 |
/**
* 获取 IP 地理位置
* 淘宝IP接口
* @Return: array
*/
function getCity($ip)
{
$url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
$ip=json_decode(file_get_contents($url));
if((string)$ip->code=='1'){
return false;
}
$data = (array)$ip->data;
return $data;
}
|
上面原因是通过file_get_contents由淘宝网返回的json格式的数据,我们再利用php json_decode函数转换成数组。
$IP地址需要我们提供,下面提供一个获取用户真实IP地址的函数
代码如下 |
复制代码 |
function getIP()
{
static $realip;
if (isset($_SERVER)){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
$realip = $_SERVER["HTTP_CLIENT_IP"];
} else {
$realip = $_SERVER["REMOTE_ADDR"];
}
} else {
if (getenv("HTTP_X_FORWARDED_FOR")){
$realip = getenv("HTTP_X_FORWARDED_FOR");
} else if (getenv("HTTP_CLIENT_IP")) {
$realip = getenv("HTTP_CLIENT_IP");
} else {
$realip = getenv("REMOTE_ADDR");
}
}
return $realip;
}
|