使用淘寶免費 IP 定位 API(https://ip.taobao.com/service/getIpInfo.php)快速取得訪客城市、ISP 等資訊,含完整封裝函式與跨代理取真實 IP 方法。
function getRealIp() {
$headers = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'REMOTE_ADDR'
];
foreach ($headers as $header) {
if (!empty($_SERVER[$header]) && strcasecmp($_SERVER[$header], 'unknown')) {
// X-Forwarded-For 可能包含多個 IP,取第一個
$ips = explode(',', $_SERVER[$header]);
return trim($ips[0]);
}
}
return 'unknown';
}
function getLocationByIp($ip) {
$url = "https://ip.taobao.com/service/getIpInfo.php?ip=$ip";
$json = @file_get_contents($url);
if (!$json) return false;
$data = json_decode($json, true);
if (($data['code'] ?? 1) !== 0) return false;
return $data['data'] ?? false;
}
// 使用範例
$ip = getRealIp();
$location = getLocationByIp($ip);
if ($location) {
echo "國家:{$location['country']}
";
echo "地區:{$location['area']}
";
echo "省份:{$location['region']}
";
echo "城市:{$location['city']}
";
echo "ISP:{$location['isp']}
";
} else {
echo "無法解析 IP 位置";
}
Array
(
[code] => 0
[data] => Array
(
[country] => 中國
[country_id] => CN
[area] => 華南
[area_id] => 800000
[region] => 廣東省
[region_id] => 440000
[city] => 深圳市
[city_id] => 440300
[county] =>
[county_id] => -1
[isp] => 電信
[isp_id] => 100017
[ip] => 183.16.191.102
)
)
file_get_contents 不受影響。