function getClientIp(): string {
$headers = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
];
foreach ($headers as $header) {
if (!empty($_SERVER[$header])) {
// X-Forwarded-For 可能包含多個 IP,取第一個(客戶端原始 IP)
$ips = explode(',', $_SERVER[$header]);
$ip = trim($ips[0]);
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
}
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 本地 IP 資料庫 | 離線、快速、無限制 | 需定期更新、精度有限 | 高頻、內網、隱私敏感 |
| 第三方 API | 精度高、免維護 | 頻率限制、網路延遲、隱私 | 低頻、原型開發 |
| MaxMind GeoIP2 | 業界標準、精度高 | 需授權、二進位格式 | 企業級應用 |
class IpLocation {
private string $dbPath;
private int $recordLength;
public function __construct(string $dbPath = __DIR__ . '/data/ip.dat') {
$this->dbPath = $dbPath;
$this->recordLength = 17 + 22 + 13 + 47 + 12 + 1; // 依格式調整
}
public function lookup(string $ip = ''): string {
$ip = $ip ?: getClientIp();
if ($ip === '127.0.0.1') return '本地回環';
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return '無效 IPv4';
}
$fp = fopen($this->dbPath, 'rb');
if (!$fp) return '資料庫開啟失敗';
// 二分搜尋邏輯...
fclose($fp);
return '未知地址';
}
}
# 安裝
composer require geoip2/geoip2:~2.0
# 使用
use GeoIp2\Database\Reader;
$reader = new Reader('/path/to/GeoLite2-City.mmdb');
$record = $reader->city($ip);
echo $record->country->name; // 國家
echo $record->city->name; // 城市
echo $record->location->latitude; // 緯度
echo $record->mostSpecificSubdivision->name; // 省/州
function lookupApi(string $ip): ?array {
$url = "https://ip-api.com/json/{$ip}?lang=zh-TW";
$json = @file_get_contents($url);
if (!$json) return null;
$data = json_decode($json, true);
return $data['status'] === 'success' ? $data : null;
}
原始來源:www.111cn.net