php获取ip地址及详情

2017-05-08  本文已影响163人  fuyou2324

1. 获取ip地址

header("Content-type: text/html; charset=utf-8");
 
function getCity($ip = '')//获取地区
{
    if($ip == ''){
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";//新浪借口获取访问者地区
        $ip=json_decode(file_get_contents($url),true);
        $data = $ip;
    }else{
        $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;//淘宝借口需要填写ip
        $ip=json_decode(file_get_contents($url));  
        if((string)$ip->code=='1'){
           return false;
        }
        $data = (array)$ip->data;
    }
     
    return $data;  
}
 
print_r($city);
 
 
//获取访问者ip地址
 
if ($_SERVER['REMOTE_ADDR']) {//判断SERVER里面有没有ip,因为用户访问的时候会自动给你网这里面存入一个ip
     $cip = $_SERVER['REMOTE_ADDR'];
} elseif (getenv("REMOTE_ADDR")) {//如果没有去系统变量里面取一次 getenv()取系统变量的方法名字
     $cip = getenv("REMOTE_ADDR");
} elseif (getenv("HTTP_CLIENT_IP")) {//如果还没有在去系统变量里取下客户端的ip
     $cip = getenv("HTTP_CLIENT_IP");
} else {
     $cip = "unknown";
}
     echo $cip;

2. 解析数据json_decode

    淘宝接口 :
    {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u5e7f\u897f","city":"\u6842\u6797","district":"","isp":"","type":"","desc":""}
    
json_decode后:
    array (
          'ret' => '1',
          'start' => '-1',
          'end' => '-1',
          'country' => '中国',
          'province' => '广西',
          'city' => '桂林',
          'district' => '',
          'isp' => '',
          'type' => '',
          'desc' => '',
    );
    
上一篇下一篇

猜你喜欢

热点阅读