/**
* 调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 '未知地区';
}
}
curl调taobao接口获取ip地址信息(国内或者国外,代理没办法)
最新推荐文章于 2025-03-03 18:38:16 发布