萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 取得用戶真實 IP 並查詢地理位置:代理穿透、IP 資料庫、Composer 套件推薦

取得 Client IP(支援代理穿透)

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 地理位置查詢方案比較

方案優點缺點適用場景
本地 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 套件(推薦)

# 安裝
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; // 省/州

方案三:免費 API 範例

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;
}

隱私與合規提醒

  • GDPR/個資法:IP 視為個人資料,需告知、取得同意、提供刪除機制
  • 避免記錄完整 IP,可哈希或截斷最後一段
  • 第三方 API 傳送 IP 需評估資料傳輸合規性

原始來源:www.111cn.net

copyright © 萬盛學電腦網 all rights reserved