萬盛學電腦網

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

PHP 取得客戶端 IP 與地理位置 (新浪 IP 庫)

前言

取得訪客真實 IP 並查詢地理位置是常見需求。本文提供完整類別,支援多層 Proxy 真實 IP 偵測、新浪 IP 定位介面 (HTTP/JSON)、快取機制、多種輸出格式。

完整 IP 定位類別

<?php
class IpLocator
{
    private $config = [];
    private $cacheDir;
    private $cacheTtl = 86400; // 24 小時快取 IP 定位結果

    public function __construct(array $config = [])
    {
        $this->config = array_merge([
            'only_ip' => false,
            'format' => 'json', // json, array, xml, raw
            'echo' => false,
            'cache' => true,
            'api_url' => 'https://int.dpool.sina.com.cn/iplookup/iplookup.php',
        ], $config);

        $this->cacheDir = sys_get_temp_dir() . '/ip_locator_cache/';
        if (!is_dir($this->cacheDir)) @mkdir($this->cacheDir, 0755, true);
    }

    public function locate(string $ip = ''): mixed
    {
        $ip = $ip ?: $this->getClientIp();
        if (!$this->isValidIp($ip)) {
            return $this->output(['error' => 'Invalid IP']);
        }

        // 僅回傳 IP
        if ($this->config['only_ip']) {
            return $this->output($ip);
        }

        // 快取檢查
        $cacheFile = $this->cacheDir . md5($ip) . '.json';
        if ($this->config['cache'] && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $this->cacheTtl)) {
            $cached = json_decode(file_get_contents($cacheFile), true);
            return $this->output($cached);
        }

        // 呼叫新浪 API
        $url = $this->config['api_url'] . '?ip=' . urlencode($ip) . '&format=json';
        $context = stream_context_create([
            'http' => ['timeout' => 5, 'user_agent' => 'PHP IpLocator/1.0'],
        ]);
        $response = @file_get_contents($url, false, $context);

        if (!$response) {
            return $this->output(['error' => 'API request failed', 'ip' => $ip]);
        }

        // 新浪 API 回傳 GBK 編碼 JSON
        $response = mb_convert_encoding($response, 'UTF-8', 'GBK');
        $data = json_decode($response, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            return $this->output(['error' => 'JSON parse failed', 'raw' => $response]);
        }

        // 正規化欄位
        $result = [
            'ip' => $ip,
            'country' => $data['country'] ?? '',
            'province' => $data['province'] ?? '',
            'city' => $data['city'] ?? '',
            'district' => $data['district'] ?? '',
            'isp' => $data['isp'] ?? '',
            'type' => $data['type'] ?? '',
            'lat' => $data['lat'] ?? '',
            'lng' => $data['lng'] ?? '',
        ];

        // 寫入快取
        if ($this->config['cache']) {
            @file_put_contents($cacheFile, json_encode($result, JSON_UNESCAPED_UNICODE));
        }

        return $this->output($result);
    }

    private function getClientIp(): string
    {
        $headers = [
            'HTTP_CF_CONNECTING_IP',     // Cloudflare
            'HTTP_X_FORWARDED_FOR',      // 標準代理
            'HTTP_X_REAL_IP',            // Nginx
            'HTTP_CLIENT_IP',
            'REMOTE_ADDR',
        ];

        foreach ($headers as $header) {
            if (!empty($_SERVER[$header])) {
                $ips = array_map('trim', explode(',', $_SERVER[$header]));
                foreach ($ips as $ip) {
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                        return $ip;
                    }
                }
                // 兜底:回傳第一個有效 IP (含私有)
                foreach ($ips as $ip) {
                    if (filter_var($ip, FILTER_VALIDATE_IP)) return $ip;
                }
            }
        }
        return '0.0.0.0';
    }

    private function isValidIp(string $ip): bool
    {
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
    }

    private function output(mixed $data): mixed
    {
        if ($this->config['echo']) {
            switch ($this->config['format']) {
                case 'json':
                    header('Content-Type: application/json; charset=UTF-8');
                    echo json_encode($data, JSON_UNESCAPED_UNICODE);
                    break;
                case 'xml':
                    header('Content-Type: application/xml; charset=UTF-8');
                    echo $this->arrayToXml($data);
                    break;
                case 'array':
                    print_r($data);
                    break;
                default:
                    echo $data;
            }
            return true;
        }
        return $this->config['format'] === 'json' ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
    }

    private function arrayToXml(array $data, string $root = 'result'): string
    {
        $xml = new SimpleXMLElement("<$root/>");
        array_walk_recursive($data, [$xml, 'addChild']);
        return $xml->asXML();
    }
}

// 使用範例
// 1. 直接輸出 JSON
new IpLocator(['format' => 'json', 'echo' => true])->locate();

// 2. 取得陣列
$locator = new IpLocator(['format' => 'array']);
$result = $locator->locate('8.8.8.8');
print_r($result);

// 3. 僅取得 IP
$ip = (new IpLocator(['only_ip' => true, 'format' => 'json']))->locate();
echo $ip;
?>

前端 JavaScript 整合

<script>
// 由 PHP 直接輸入 JS 變數
var clientIp = "<?php (new IpLocator(['only_ip'=>true, 'echo'=>true]))->locate(); ?>";
var locationData = <?php (new IpLocator(['format'=>'json', 'echo'=>true]))->locate(); ?>;

console.log('IP:', clientIp);
console.log('位置:', locationData);
// 輸出範例:
// 位置: {ip: "8.8.8.8", country: "美國", province: "加利福尼亞", city: "山景城", isp: "Google", ...}
</script>

替代方案比較

方案優點缺點適用場景
新浪 IP 庫 (本文)免費、無需註冊、支援中文地名非官方、可能失效、QPS 限制、僅 IPv4個人專案、低頻查詢
ip-api.com免費額度大 (45k/月)、JSON/CSV、HTTPS商業用途需付費、需註冊中小專案
MaxMind GeoIP2精準、離線資料庫、企業級付費、需定期更新資料庫高精度需求、生產環境
IP2Location多語言支援、豐富欄位付費企業應用
Cloudflare CF-IPCountry無需額外請求、Header 直接可用僅國家代碼、需使用 CF CDN已接入 Cloudflare 的站點

總結

IpLocator 類別封裝了 IP 偵測、新浪 API 呼叫、編碼轉換、快取、多格式輸出,可直接整合專案。生產環境建議改用付費 GeoIP 服務或離線資料庫以確保穩定性與精準度。

copyright © 萬盛學電腦網 all rights reserved