淘寶提供免費 IP 地理信息查詢接口:https://ip.taobao.com/service/getIpInfo.php?ip=IP地址,返回 JSON 格式數據,含國家、地區、城市、ISP 等字段。
<?php
class TaobaoIPQuery {
private $m_ip;
private $m_content; // 解析後的 JSON 對象
public function __construct($ip) {
if (isset($ip)) {
$this->m_ip = $ip;
} else {
$this->m_ip = "";
}
if (!empty($this->m_ip)) {
$url_handle = curl_init();
curl_setopt($url_handle, CURLOPT_URL, "https://ip.taobao.com/service/getIpInfo.php?ip=" . $this->m_ip);
curl_setopt($url_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url_handle, CURLOPT_TIMEOUT, 5); // 超時保護
$this->m_content = curl_exec($url_handle);
$errno = curl_errno($url_handle);
$error = curl_error($url_handle);
curl_close($url_handle);
if ($errno) {
throw new Exception("cURL Error [$errno]: $error");
}
if ($this->m_content) {
$this->m_content = json_decode($this->m_content);
if (isset($this->m_content->code) && $this->m_content->code == 1) {
throw new Exception("Query error: " . ($this->m_content->data ?? 'Unknown'));
}
} else {
throw new Exception("Empty response from Taobao IP API");
}
} else {
throw new Exception("IP address must not be empty");
}
}
public function getRegion() { return $this->m_content->data->region ?? ''; }
public function getIsp() { return $this->m_content->data->isp ?? ''; }
public function getCountry() { return $this->m_content->data->country ?? ''; }
public function getCity() { return $this->m_content->data->city ?? ''; }
public function getArea() { return $this->m_content->data->area ?? ''; }
public function getCounty() { return $this->m_content->data->county ?? ''; }
public function getIp() { return $this->m_content->data->ip ?? ''; }
public function getAll() { return $this->m_content->data ?? new stdClass(); }
}
?>
<?php
try {
$ip = $_SERVER['REMOTE_ADDR']; // 或獲取代理後的真實 IP
$ipQuery = new TaobaoIPQuery($ip);
echo "國家: " . $ipQuery->getCountry() . "<br>";
echo "地區: " . $ipQuery->getRegion() . "<br>";
echo "城市: " . $ipQuery->getCity() . "<br>";
echo "ISP: " . $ipQuery->getIsp() . "<br>";
// 完整信息
print_r($ipQuery->getAll());
} catch (Exception $e) {
echo "IP查詢失敗: " . $e->getMessage();
// 降級處理:使用本地 GeoIP 數據庫或其他服務
}
?>
$cacheKey = "ip_info_{$ip}";
$info = $redis->get($cacheKey);
if (!$info) {
$ipQuery = new TaobaoIPQuery($ip);
$info = $ipQuery->getAll();
$redis->setex($cacheKey, 86400, json_encode($info));
}https://ip.taobao.com/...。