PHP IP 地理位置查询指南

在 PHP 中获取一个 IP 地址的国家、城市和近似坐标。

在 PHP 中查询 IP 地址

该请求接受一个 IPv4 或 IPv6 地址,并要求返回 JSON。请将示例地址替换为需要检查的地址。

单个 IP 的位置查询请求
<?php
$ip = '8.8.8.8'; // Replace with a validated IPv4 or IPv6 address.
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
    throw new InvalidArgumentException('Invalid IP address');
}
$url = 'https://api.ipquery.io/' . rawurlencode($ip) . '?format=json';
$handle = curl_init($url);
curl_setopt_array($handle, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 3,
    CURLOPT_TIMEOUT => 8,
]);
$body = curl_exec($handle);
$status = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($body === false) {
    $error = curl_error($handle);
    throw new RuntimeException('IP lookup failed: ' . $error);
}
if ($status !== 200) {
    throw new RuntimeException('IPQuery returned HTTP ' . $status);
}
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if (($data['ip'] ?? null) !== $ip || !isset($data['location']) || !is_array($data['location'])) {
    throw new RuntimeException('Unexpected IPQuery response');
}
$location = $data['location'];
$countryCode = strtoupper(trim((string) ($location['country_code'] ?? '')));
$city = trim((string) ($location['city'] ?? ''));
echo 'Country code: ' . ($countryCode ?: 'Unknown') . PHP_EOL;
echo 'City: ' . ($city ?: 'Unknown') . PHP_EOL;

// Coordinates describe an approximate network location, not the user.
$latitude = $location['latitude'] ?? null;
$longitude = $location['longitude'] ?? null;
if (preg_match('/^[A-Z]{2}$/', $countryCode) &&
    !in_array($countryCode, ['XX', 'ZZ'], true) &&
    is_numeric($latitude) && is_numeric($longitude)) {
    printf('Approximate coordinates: %.5f, %.5f%s', $latitude, $longitude, PHP_EOL);
}

需要启用 cURL 扩展的 PHP。连接超时为三秒,请求总时限为八秒。

读取位置字段

location.country_code 是两字母国家代码;location.country 是国家名称。即使已知国家,location.city 也可能为空。请将空值保留为未知。

location.latitude 和 location.longitude 是网络位置的近似坐标。显示前,请确认存在可用的位置名称;仅有数值坐标不足以确定位置。这些坐标不能识别设备或个人。

如需获取发起请求的连接地址,请调用 https://api.ipquery.io/?format=json. 服务器发出的请求返回服务器用于连接的 IP;浏览器发出的请求返回其连接对外可见的地址。

所有响应字段

准确性与安全性

IP 地理位置是对网络位置的估计,并非设备位置。VPN、代理、移动网络和运营商网关可能导致地址被定位到远离用户的地方。请将缺失值视为未知,不要用猜测补齐。

如果应用读取 X-Forwarded-For,仅在该标头由您控制的代理提供时才可信任。客户端提供的标头可能被伪造。发起查询请求前请验证地址,并将超时和 HTTP 错误与成功结果分别处理。

API 参考

完整列表访问。

如需价格或完整列表访问权限,请发送邮件至 contact@ipquery.io.

选定列表
选定记录
此列表中的记录