透過訪客 IP 取得地理位置(國家、城市、ISP 等)是個性化內容、安全防護、統計分析的基礎功能。本文提供完整 PHP 實作,支援多種 IP 取得方式與第三方 API 串接。
考量 Proxy、CDN、Load Balancer 等網路架構,需依序檢查多個 Header。
<?php
function getClientIP() {
$ipKeys = [
'HTTP_X_FORWARDED_FOR', // 標準代理標頭,可能包含多個 IP(逗號分隔)
'HTTP_X_REAL_IP', // Nginx proxy_set_header
'HTTP_CLIENT_IP', // 部分代理使用
'HTTP_CF_CONNECTING_IP', // Cloudflare
'REMOTE_ADDR' // 直接連線或最後防線
];
foreach ($ipKeys as $key) {
if (!empty($_SERVER[$key])) {
// X-Forwarded-For 可能包含多個 IP,取第一個(客戶端原始 IP)
$ips = explode(',', $_SERVER[$key]);
$ip = trim($ips[0]);
// 過濾私有/保留 IP 範圍
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
return '127.0.0.1'; // 回退值
}
$ip = getClientIP();
echo "Client IP: $ip\n";
<?php
function getLocationByTaobao($ip) {
$url = "https://ip.taobao.com/service/getIpInfo.php?ip=" . urlencode($ip);
$json = @file_get_contents($url);
if ($json === false) return null;
$data = json_decode($json, true);
if ($data['code'] !== 0) return null;
return [
'country' => $data['data']['country'] ?? '',
'region' => $data['data']['region'] ?? '',
'city' => $data['data']['city'] ?? '',
'isp' => $data['data']['isp'] ?? '',
'lat' => $data['data']['lat'] ?? '',
'lng' => $data['data']['lng'] ?? '',
];
}
$location = getLocationByTaobao($ip);
if ($location) {
echo "位置: {$location['country']} {$location['region']} {$location['city']} ({$location['isp']})";
}
<?php
function getLocationByIpApi($ip) {
$url = "https://ip-api.com/json/" . urlencode($ip) . "?lang=zh-TW&fields=status,message,country,regionName,city,isp,lat,lon,query";
$json = @file_get_contents($url);
if ($json === false) return null;
$data = json_decode($json, true);
if ($data['status'] !== 'success') return null;
return [
'country' => $data['country'] ?? '',
'region' => $data['regionName'] ?? '',
'city' => $data['city'] ?? '',
'isp' => $data['isp'] ?? '',
'lat' => $data['lat'] ?? '',
'lng' => $data['lon'] ?? '',
];
}
<?php
// Composer: require geoip2/geoip2:~2.0
use GeoIp2\Database\Reader;
function getLocationByMaxMind($ip, $dbPath = '/usr/share/GeoIP/GeoLite2-City.mmdb') {
if (!file_exists($dbPath)) return null;
$reader = new Reader($dbPath);
try {
$record = $reader->city($ip);
return [
'country' => $record->country->isoCode,
'countryName' => $record->country->name,
'region' => $record->mostSpecificSubdivision->name,
'city' => $record->city->name,
'isp' => $record->traits->isp ?? '',
'lat' => $record->location->latitude,
'lng' => $record->location->longitude,
];
} catch (\Exception $e) {
return null;
}
}
<?php
class IPGeoLocator {
private $apis = [];
public function __construct() {
$this->apis = [
[$this, 'taobao'],
[$this, 'ipapi'],
// 可加入 MaxMind 等
];
}
public function locate($ip = null) {
$ip = $ip ?? $this->getClientIP();
foreach ($this->apis as $api) {
$result = $api($ip);
if ($result) return array_merge(['ip' => $ip], $result);
}
return ['ip' => $ip, 'error' => 'All APIs failed'];
}
private function getClientIP() { /* 上方 getClientIP 實作 */ }
private function taobao($ip) { /* 上方 getLocationByTaobao 實作 */ }
private function ipapi($ip) { /* 上方 getLocationByIpApi 實作 */ }
}
// 使用
$locator = new IPGeoLocator();
$info = $locator->locate();
print_r($info);