PHP获取ip与ip所在城市

今天在博客园看到一篇关于如何获取ip以及ip所在城市,刚好用到,就转载一下分享给大家看看,博主昵称:TBHacker

1获取真实ip,本地测试总是::1 或者127.0.0.1 或者局域网的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;
}


2.根据ip获取地址

/**
 * 获取 IP  地理位置
 * 淘宝IP接口
 * @Return: array
 */
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=json_decode(file_get_contents($url));   
        if((string)$ip->code=='1'){
           return false;
        }
        $data = (array)$ip->data;
    }
    
    return $data;   
}


测试:

var_dump(getIP());
var_dump(getCity());
var_dump(getCity('218.93.250.162'));
结果:
string(3) "::1"
array(10) {
  ["ret"]=>
  int(1)
  ["start"]=>
  int(-1)
  ["end"]=>
  int(-1)
  ["country"]=>
  string(6) "中国"
  ["province"]=>
  string(6) "江苏"
  ["city"]=>
  string(6) "宿迁"
  ["district"]=>
  string(0) ""
  ["isp"]=>
  string(0) ""
  ["type"]=>
  string(0) ""
  ["desc"]=>
  string(0) ""
}
array(13) {
  ["country"]=>
  string(6) "中国"
  ["country_id"]=>
  string(2) "CN"
  ["area"]=>
  string(6) "华东"
  ["area_id"]=>
  string(6) "300000"
  ["region"]=>
  string(9) "江苏省"
  ["region_id"]=>
  string(6) "320000"
  ["city"]=>
  string(9) "宿迁市"
  ["city_id"]=>
  string(6) "321300"
  ["county"]=>
  string(0) ""
  ["county_id"]=>
  string(2) "-1"
  ["isp"]=>
  string(6) "电信"
  ["isp_id"]=>
  string(6) "100017"
  ["ip"]=>
  string(14) "218.93.250.162"
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值