curl调taobao接口获取ip地址信息(国内或者国外,代理没办法)

本文介绍了一个PHP函数,用于通过调用Taobao的API来获取指定IP地址的地理位置信息。该函数首先检查输入的IP地址,然后使用cURL发起HTTP请求到Taobao的服务接口,获取并解析JSON响应,最后根据解析结果返回相应的地区信息。如果IP地址无效或无法获取信息,则返回'未知地区'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 调taobao接口获取ip地址信息
 * @param $ip
 * @param bool $raw
 * @return mixed|string
 */
function getRegionByIp($ip, $raw = false)
{
    // 115.156.238.114
    // {"code":0,"data":{"ip":"115.156.238.114","country":"中国","area":"","region":"湖北","city":"武汉","county":"XX","isp":"教育网","country_id":"CN","area_id":"","region_id":"420000","city_id":"420100","county_id":"xx","isp_id":"100027"}}

    // xxx 不正确的ip
    // {"code":0,"data":{"ip":"115.156.","country":"","area":"","region":"","city":"","county":"","isp":"","country_id":"","area_id":"","region_id":"","city_id":"","county_id":"","isp_id":""}}

    // 192.168.1.2
    // {"code":0,"data":{"ip":"192.168.0.123","country":"XX","area":"","region":"XX","city":"内网IP","county":"内网IP","isp":"内网IP","country_id":"xx","area_id":"","region_id":"xx","city_id":"local","county_id":"local","isp_id":"local"}}

    if (!$ip) return '未知地区';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    $http_resp = curl_exec($ch);
    curl_close($ch);
    $res = json_decode($http_resp, true);
    
    // 是否要转为数组
    if ($raw) {
        return $res;
    }
    $country_id = $res['data']['country_id'];

    /**************是否有效***********/
    // taobao 的接口内网地址会返回xx, 不合法IP会返回空字符串
    $is_valid = !in_array($country_id, ['xx', '']); 
    if ($is_valid) {
        if ($country_id != 'CN') {
            return '国外';
        }
        return $res['data']['region'] . ' ' . $res['data']['city'];
    } else {
        return '未知地区';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值