萬盛學電腦網

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

PHP IP 白名單/區間訪問控制實現方案

需求

限制只有特定 IP 或 IP 段(如公司出口 IP、合作夥伴網段)能訪問管理後台、內部 API 等敏感資源。

核心工具函數

<?php
/**
 * 獲取客戶端真實 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,取第一個(最原始客戶端)
            $ips = explode(',', $_SERVER[$header]);
            return trim($ips[0]);
        }
    }
    return '0.0.0.0';
}

/**
 * 判斷 IP 是否在指定區間內
 * @param string $ip      待檢測 IP
 * @param string $start   起始 IP
 * @param string $end     結束 IP(可選,省略則精確匹配)
 * @return bool
 */
function inIpRange(string $ip, string $start, ?string $end = null): bool {
    $ipLong = ip2long($ip);
    if ($ipLong === false) return false;

    $startLong = ip2long($start);
    if ($startLong === false) return false;

    if ($end === null) {
        return $ipLong === $startLong;
    }

    $endLong = ip2long($end);
    if ($endLong === false) return false;

    // ip2long 返回有符號整數,需轉無符號比較
    $ipLong   = sprintf('%u', $ipLong);
    $startLong = sprintf('%u', $startLong);
    $endLong   = sprintf('%u', $endLong);

    return $ipLong >= $startLong && $ipLong <= $endLong;
}

/**
 * CIDR 寫法支援(如 192.168.1.0/24)
 */
function inCidrRange(string $ip, string $cidr): bool {
    [$subnet, $mask] = explode('/', $cidr);
    $mask = (int)$mask;
    $ipLong = sprintf('%u', ip2long($ip));
    $subnetLong = sprintf('%u', ip2long($subnet));
    $maskLong = ~((1 << (32 - $mask)) - 1);
    return ($ipLong & $maskLong) === ($subnetLong & $maskLong);
}

訪問控制中間件

<?php
function authorizeIpAccess(): void {
    $clientIp = getClientIp();

    // 允許列表:支援單 IP、區間、CIDR
    $allowList = [
        '127.0.0.1',                    // 本地
        '10.0.0.0/8',                   // 內網 A 類
        '192.168.0.0/16',               // 內網 C 類
        '203.0.113.0/24',               // 公司公網出口段
        ['212.76.229.115', '212.76.229.120'], // 區間寫法
    ];

    $allowed = false;
    foreach ($allowList as $rule) {
        if (is_array($rule)) {
            // 區間:[start, end]
            if (inIpRange($clientIp, $rule[0], $rule[1])) { $allowed = true; break; }
        } elseif (strpos($rule, '/') !== false) {
            // CIDR
            if (inCidrRange($clientIp, $rule)) { $allowed = true; break; }
        } else {
            // 單 IP
            if (inIpRange($clientIp, $rule)) { $allowed = true; break; }
        }
    }

    if (!$allowed) {
        // 記錄拒絕日誌
        error_log("[IP_BLOCK] Denied: $clientIp at " . date('c'));
        // 返回 403 或重定向
        http_response_code(403);
        exit('Access Denied: Your IP (' . $clientIp . ') is not allowed.');
    }
}

// 在入口文件最頂部調用
authorizeIpAccess();

IPv6 支援補充

上述 ip2long 僅支援 IPv4。現代項目需支援 IPv6,建議引用 symfony/polyfill-php72 的 inet_pton 或直接使用 Webmozart\Assert\Ip 等庫。簡易版 IPv6 區間判斷:

function inIpRangeV6(string $ip, string $start, string $end): bool {
    $ipBin = inet_pton($ip);
    $startBin = inet_pton($start);
    $endBin = inet_pton($end);
    return $ipBin >= $startBin && $ipBin <= $endBin;
}

部署建議

  • 放在 Nginx allow/deny 或 Cloudflare WAF 層面更高效,PHP 層作為二道防線。
  • 代理環境下確保 real_ip_header 配置正確,避免獲取到代理 IP。
  • 白名單變更建議熱加載(如讀取 Redis/配置中心),避免頻繁發布代碼。

總結

通過 ip2long 無符號比較實現 IPv4 區間判斷,結合 CIDR 解析、代理穿透獲取真實 IP,構建靈活的訪問控制中間件。生產環境建議優先在網關層攔截,PHP 層作為兜底與業務邏輯結合點。

copyright © 萬盛學電腦網 all rights reserved