在反向代理 (Nginx)、負載均衡 (SLB/ALB)、CDN (Cloudflare) 等架構下,$_SERVER['REMOTE_ADDR'] 往往是代理伺服器 IP,而非真實客戶端 IP。需依序檢查多個 HTTP 頭部並驗證有效性。
HTTP_CLIENT_IP:部分代理設置 (較少見)HTTP_X_FORWARDED_FOR:標準代理頭,格式 client, proxy1, proxy2,取第一個HTTP_X_REAL_IP:Nginx proxy_set_header X-Real-IP 設置HTTP_CF_CONNECTING_IP:Cloudflare 專用真實 IPHTTP_X_FORWARDED、HTTP_FORWARDED_FOR、HTTP_FORWARDED:其他變體REMOTE_ADDR:最後兜底,直連或無代理時<?php
declare(strict_types=1);
class IpDetector
{
// 受信任代理 IP 範圍 (CIDR),防止偽造頭部
private array $trustedProxies = [
'10.0.0.0/8', // RFC1918 私有網段
'172.16.0.0/12',
'192.168.0.0/16',
'127.0.0.0/8', // 本地回環
// 雲廠商 IP 範圍 (需定期更新)
// '13.32.0.0/15', // Cloudflare
// '52.0.0.0/8', // AWS ALB
];
// 標準頭部優先級
private array $headers = [
'HTTP_CF_CONNECTING_IP', // Cloudflare
'HTTP_X_REAL_IP', // Nginx 標準
'HTTP_X_FORWARDED_FOR', // 標準代理鏈
'HTTP_CLIENT_IP', // 少見
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR', // 兜底
];
public function getClientIp(): string
{
foreach ($this->headers as $header) {
$value = $_SERVER[$header] ?? '';
if ($value === '') continue;
// X-Forwarded-For 可能包含多個 IP,取第一個 (客戶端)
$ips = array_map('trim', explode(',', $value));
$clientIp = $ips[0];
if ($this->isValidIp($clientIp)) {
// 驗證請求來源是否為受信任代理
$remoteAddr = $_SERVER['REMOTE_ADDR'] ?? '';
if ($this->isTrustedProxy($remoteAddr)) {
return $clientIp;
}
// 若非受信任代理,僅允許直接連線
if ($header === 'REMOTE_ADDR') {
return $clientIp;
}
}
}
return 'unknown';
}
public function getClientIpFull(): array
{
$ip = $this->getClientIp();
return [
'ip' => $ip,
'is_ipv4' => filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false,
'is_ipv6' => filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false,
'is_private' => $this->isPrivateIp($ip),
'is_loopback' => $this->isLoopback($ip),
];
}
private function isValidIp(string $ip): bool
{
return filter_var($ip, FILTER_VALIDATE_IP) !== false;
}
private function isPrivateIp(string $ip): bool
{
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false;
}
private function isLoopback(string $ip): bool
{
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false
&& (str_starts_with($ip, '127.') || $ip === '::1');
}
private function isTrustedProxy(string $proxyIp): bool
{
if (!$this->isValidIp($proxyIp)) return false;
foreach ($this->trustedProxies as $cidr) {
if ($this->ipInCidr($proxyIp, $cidr)) return true;
}
return false;
}
private function ipInCidr(string $ip, string $cidr): bool
{
[$range, $bits] = explode('/', $cidr);
$mask = ~((1 << (32 - $bits)) - 1);
$ipLong = ip2long($ip);
$rangeLong = ip2long($range);
// IPv6 簡化處理:這裡僅示範 IPv4
if ($ipLong === false || $rangeLong === false) return false;
return ($ipLong & $mask) === ($rangeLong & $mask);
}
// 允許動態添加受信任代理 (如從配置檔載入)
public function addTrustedProxy(string $cidr): void
{
$this->trustedProxies[] = $cidr;
}
}
// 使用範例
$detector = new IpDetector();
// 動態添加雲廠商 IP 範圍 (建議從配置檔讀取)
$detector->addTrustedProxy('13.32.0.0/15'); // Cloudflare
$detector->addTrustedProxy('52.0.0.0/8'); // AWS
$ipInfo = $detector->getClientIpFull();
echo "客戶端 IP: {$ipInfo['ip']}\n";
echo "IPv4: " . ($ipInfo['is_ipv4'] ? '是' : '否') . "\n";
echo "IPv6: " . ($ipInfo['is_ipv6'] ? '是' : '否') . "\n";
echo "私有 IP: " . ($ipInfo['is_private'] ? '是' : '否') . "\n";
echo "回環地址: " . ($ipInfo['is_loopback'] ? '是' : '否') . "\n";
?>
# nginx.conf
# 真實 IP 傳遞
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 若使用 realip 模塊 (需編譯 --with-http_realip_module)
set_real_ip_from 10.0.0.0/8;
set_real_ip_from 172.16.0.0/12;
set_real_ip_from 192.168.0.0/16;
set_real_ip_from 13.32.0.0/15; # Cloudflare
real_ip_header X-Forwarded-For;
real_ip_recursive on;
<?php
function getCloudflareRealIp(): ?string
{
// Cloudflare 專用頭部,不可偽造 (需開啟 Orange Cloud)
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
if (filter_var($ip, FILTER_VALIDATE_IP)) {
return $ip;
}
}
return null;
}
// 結合使用
$realIp = getCloudflareRealIp() ?? (new IpDetector())->getClientIp();
?>
filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) 驗證 IPv6inet_pton() / inet_ntop() 二進位轉換VARBINARY(16) 儲存 inet_pton() 結果,或 VARCHAR(45) 儲存字串ipv6-toolkit)X-Forwarded-For 完整鏈路供審計access_log 包含 $http_x_forwarded_for 而非 $remote_addr<?php
// Laravel: 信任代理中介軟體
// app/Http/Middleware/TrustProxies.php
protected $proxies = '*'; // 或具體 IP 陣列
protected $headers = Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO;
// Symfony: Request::setTrustedProxies()
Request::setTrustedProxies(['10.0.0.0/8', '192.168.0.0/16'], Request::HEADER_X_FORWARDED_FOR);
// CodeIgniter 4: Config/App.php
public $proxyIPs = '10.0.0.0/8,172.16.0.0/12,192.168.0.0/16';
獲取真實 IP 核心在於:按優先級檢查標準頭部、驗證 IP 格式、白名單驗證代理來源、支援 IPv6、配合基礎設施配置。切勿直接信任 $_SERVER['REMOTE_ADDR'] 或單一頭部,務必建立如本文 IpDetector 類般的防禦性獲取邏輯,並根據部署架構動態維護受信任代理清單。