萬盛學電腦網

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

PHP 基於 IP 地址自動跳轉至城市分站實作方案

業務場景

多城市分站系統(如分類資訊、招聘、房產平台)需根據訪客 IP 自動導向對應城市子站,提升用戶體驗與轉化率。本文提供基於純真 IP 庫(QQWry.dat)的完整 PHP 實作方案。

核心組件

  1. QQWry.dat:純真 IP 數據庫文件(需定期更新,約 8MB)
  2. QQWry 類別:解析 .dat 格式、二分查找 IP 範圍、提取地區資訊
  3. 城市映射表:將 IP 庫返回的省/市名稱映射至系統站點域名/ID
  4. 跳轉邏輯:首次訪問判斷、Cookie 記錄用戶選擇、避免重複跳轉

完整實作代碼

1. IP 解析核心類 IpLocation.php

<?php
/**
 * 純真 IP 庫解析器(支援 QQWry.dat 格式)
 * 參考:https://github.com/superspring/php-qqwry
 */
class IpLocation {
    private $fp;
    private $firstStartIp;
    private $lastStartIp;
    private $totalRecords;
    private $dbPath;

    public function __construct(string $dbPath = __DIR__ . '/QQWry.dat') {
        $this->dbPath = $dbPath;
        $this->init();
    }

    private function init(): void {
        if (!file_exists($this->dbPath)) {
            throw new RuntimeException("IP 數據庫文件不存在:{$this->dbPath}");
        }
        $this->fp = fopen($this->dbPath, 'rb');
        if (!$this->fp) {
            throw new RuntimeException("無法打開 IP 數據庫文件");
        }
        
        // 讀取文件頭:首記錄偏移、末記錄偏移
        $header = fread($this->fp, 8);
        $this->firstStartIp = $this->readInt32($header, 0);
        $this->lastStartIp = $this->readInt32($header, 4);
        $this->totalRecords = ($this->lastStartIp - $this->firstStartIp) / 7;
        
        if ($this->totalRecords <= 1) {
            throw new RuntimeException('IP 數據庫格式錯誤或為空');
        }
    }

    /**
     * 查詢 IP 地址歸屬地
     * @param string $ip IPv4 格式
     * @return array ['country'=>國家/省, 'area'=>地區/市, 'ip'=>原始IP]
     */
    public function query(string $ip): array {
        // 內網/本地 IP 直接返回
        if ($this->isPrivateIp($ip)) {
            return ['country' => '內網', 'area' => 'Local', 'ip' => $ip];
        }

        $ipLong = $this->ip2long($ip);
        if ($ipLong === false) {
            return ['country' => '未知', 'area' => '', 'ip' => $ip];
        }

        // 二分查找記錄索引
        $left = 0;
        $right = $this->totalRecords - 1;
        $targetOffset = 0;

        while ($left <= $right) {
            $mid = (int)(($left + $right) / 2);
            $offset = $this->firstStartIp + $mid * 7;
            fseek($this->fp, $offset);
            $buf = fread($this->fp, 7);
            $curStartIp = $this->readInt32($buf, 0);
            $recEndOffset = $this->readInt24($buf, 4);

            if ($ipLong < $curStartIp) {
                $right = $mid - 1;
            } elseif ($ipLong > $this->getEndIp($recEndOffset)) {
                $left = $mid + 1;
            } else {
                $targetOffset = $recEndOffset;
                break;
            }
        }

        if ($targetOffset === 0) {
            return ['country' => '未知', 'area' => '', 'ip' => $ip];
        }

        // 解析國家/地區信息
        fseek($this->fp, $targetOffset + 4);
        $flag = ord(fread($this->fp, 1));
        
        $country = '';
        $area = '';
        
        if ($flag === 0x01 || $flag === 0x02) {
            // 重定向模式
            $countryOffset = $this->readInt24(fread($this->fp, 3), 0);
            $country = $this->readString($countryOffset);
            
            if ($flag === 0x02) {
                $area = $this->readString($targetOffset + 8);
            } else {
                $area = $this->readString(ftell($this->fp));
            }
        } else {
            // 直接模式
            fseek($this->fp, $targetOffset + 4);
            $country = $this->readString($targetOffset + 4);
            $area = $this->readString(ftell($this->fp));
        }

        return [
            'country' => $this->clean($country),
            'area' => $this->clean($area),
            'ip' => $ip
        ];
    }

    private function getEndIp(int $offset): int {
        fseek($this->fp, $offset);
        $buf = fread($this->fp, 4);
        return $this->readInt32($buf, 0);
    }

    private function readString(int $offset): string {
        fseek($this->fp, $offset);
        $str = '';
        while (($char = fread($this->fp, 1)) !== false) {
            if ($char === "\0") break;
            $str .= $char;
        }
        return $str;
    }

    private function readInt32(string $bytes, int $pos = 0): int {
        return ord($bytes[$pos]) 
            | (ord($bytes[$pos+1]) << 8)
            | (ord($bytes[$pos+2]) << 16)
            | (ord($bytes[$pos+3]) << 24);
    }

    private function readInt24(string $bytes, int $pos = 0): int {
        return ord($bytes[$pos]) 
            | (ord($bytes[$pos+1]) << 8)
            | (ord($bytes[$pos+2]) << 16);
    }

    private function ip2long(string $ip): int|false {
        $parts = explode('.', $ip);
        if (count($parts) !== 4) return false;
        foreach ($parts as $part) {
            $n = (int)$part;
            if ($n < 0 || $n > 255) return false;
        }
        return ($parts[0] << 24) | ($parts[1] << 16) | ($parts[2] << 8) | $parts[3];
    }

    private function isPrivateIp(string $ip): bool {
        return preg_match('/^(127|10|172\.(1[6-9]|2[0-9]|3[01])|192\.168)\./', $ip) === 1;
    }

    private function clean(string $str): string {
        return str_replace(['area error', 'CZ88.NET'], '', $str);
    }

    public function __destruct() {
        if (is_resource($this->fp)) fclose($this->fp);
    }
}
?>

2. 城市映射與跳轉控制器 CityRouter.php

<?php
require_once 'IpLocation.php';

class CityRouter {
    private $ipLocator;
    private $cityMap;      // IP 庫地區名 => 站點標識
    private $defaultCity;  // 預設城市
    private $cookieName = 'selected_city';
    private $cookieExpire = 86400 * 30; // 30 天

    public function __construct(array $config = []) {
        $this->ipLocator = new IpLocation($config['db_path'] ?? __DIR__ . '/QQWry.dat');
        $this->cityMap = $config['city_map'] ?? [];
        $this->defaultCity = $config['default_city'] ?? 'beijing';
    }

    /**
     * 獲取當前應導向的城市標識
     * 優先級:用戶手動選擇 > IP 自動判斷 > 預設城市
     */
    public function getTargetCity(): string {
        // 1. 檢查用戶是否已手動選擇
        if (isset($_COOKIE[$this->cookieName]) && $this->isValidCity($_COOKIE[$this->cookieName])) {
            return $_COOKIE[$this->cookieName];
        }

        // 2. 獲取客戶端真實 IP
        $clientIp = $this->getClientIp();
        
        // 3. IP 歸屬地查詢
        $location = $this->ipLocator->query($clientIp);
        
        // 4. 映射到站點城市
        $cityKey = $this->mapToCity($location['country'], $location['area']);
        
        return $cityKey ?: $this->defaultCity;
    }

    /**
     * 執行跳轉(在輸出任何內容前調用)
     */
    public function redirect(): void {
        $targetCity = $this->getTargetCity();
        $currentCity = $this->getCurrentCityFromDomain(); // 需根據實際域名結構實現
        
        if ($targetCity !== $currentCity) {
            $targetUrl = $this->buildCityUrl($targetCity);
            header("Location: $targetUrl", true, 302);
            exit;
        }
    }

    /**
     * 用戶手動切換城市
     */
    public function switchCity(string $cityKey): void {
        if ($this->isValidCity($cityKey)) {
            setcookie($this->cookieName, $cityKey, [
                'expires' => time() + $this->cookieExpire,
                'path' => '/',
                'domain' => $this->getRootDomain(),
                'secure' => isset($_SERVER['HTTPS']),
                'httponly' => true,
                'samesite' => 'Lax',
            ]);
        }
    }

    // --- 私有輔助方法 ---
    private 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])) {
                $ips = explode(',', $_SERVER[$header]);
                foreach ($ips as $ip) {
                    $ip = trim($ip);
                    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';
    }

    private function mapToCity(string $province, string $city): ?string {
        // 組合鍵名優先匹配:省+市、市、省
        $keys = [
            trim($province) . trim($city),
            trim($city),
            trim($province),
        ];
        foreach ($keys as $key) {
            if (isset($this->cityMap[$key])) return $this->cityMap[$key];
        }
        return null;
    }

    private function isValidCity(string $key): bool {
        return in_array($key, array_values($this->cityMap), true) || $key === $this->defaultCity;
    }

    private function getCurrentCityFromDomain(): string {
        // 示例:beijing.example.com -> beijing
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $parts = explode('.', $host);
        return $parts[0] ?? $this->defaultCity;
    }

    private function buildCityUrl(string $cityKey): string {
        $scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
        $root = $this->getRootDomain();
        return "$scheme://$cityKey.$root" . ($_SERVER['REQUEST_URI'] ?? '/');
    }

    private function getRootDomain(): string {
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $parts = explode('.', $host);
        return count($parts) >= 2 ? implode('.', array_slice($parts, -2)) : $host;
    }
}
?>

3. 入口文件整合 index.php

<?php
require_once 'CityRouter.php';

// 城市映射配置(根據實際 IP 庫返回值調整)
$cityMap = [
    '北京市' => 'beijing',
    '上海市' => 'shanghai',
    '廣東省廣州市' => 'guangzhou',
    '廣東省深圳市' => 'shenzhen',
    '浙江省杭州市' => 'hangzhou',
    '江蘇省南京市' => 'nanjing',
    // ... 更多映射
];

$router = new CityRouter([
    'db_path' => __DIR__ . '/data/QQWry.dat',
    'city_map' => $cityMap,
    'default_city' => 'beijing',
]);

// 1. 處理用戶手動切換城市請求
if (isset($_GET['switch_city'])) {
    $router->switchCity($_GET['switch_city']);
    // 重定向回當前頁或首頁
    header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? '/'));
    exit;
}

// 2. 執行自動跳轉(必須在任何輸出前)
$router->redirect();

// 3. 正常業務邏輯...
$currentCity = $router->getTargetCity();
echo "當前站點:$currentCity";
// 載入對應城市數據、模板等
?>

部署與維護要點

IP 數據庫更新

  • 純真數據庫約每月更新一次,建議設置定時任務自動下載最新版:
    wget -O /path/to/QQWry.dat https://update.cz88.net/soft/qqwry.rar && unrar e -y qqwry.rar QQWry.dat
  • 生產環境建議使用更精準的商業 IP 庫(如 IP2Location、MaxMind GeoIP2)或騰訊/阿雲位置服務 API。

效能優化

  • 緩存查詢結果:使用 Redis 緩存 IP 查詢結果(TTL 24h),避免重複讀取 .dat 文件。
  • 內存映射:高併發場景可將 .dat 全量讀入內存(約 8MB),使用 mmap 或 PHP 擴展加速。
  • 非阻塞跳轉:跳轉邏輯放在 Nginx `access_by_lua` 階段(OpenResty)或雲端 WAF 邊緣節點執行,減輕 PHP-FPM 壓力。

用戶體驗細節

  • 提供「切換城市」入口,並記錄用戶選擇(Cookie),尊重用戶意願。
  • 首次自動跳轉時可顯示彈窗提示「檢測到您在 [城市],是否切換到 [城市] 分站?」
  • 搜索引擎爬蟲(識別 User-Agent)不應跳轉,返回通用頁面或帶 `hreflang` 的多城市列表頁。

總結

基於 IP 的城市分站跳轉是多地業務系統的標準功能。本文提供了從底層 IP 解析、城市映射、跳轉控制到部署優化的完整方案。實際項目中建議根據流量規模選擇適合的 IP 庫與架構層級(PHP 層 vs Nginx/Lua 層 vs CDN 邊緣),並重視數據庫更新機制與用戶選擇權的保障。

copyright © 萬盛學電腦網 all rights reserved