CDN/反向代理轉發請求時,會在 Header 中附加原始客戶端 IP:
HTTP_CLIENT_IP:部分代理使用HTTP_X_FORWARDED_FOR(XFF):標準代理鏈,格式 client, proxy1, proxy2REMOTE_ADDR:直接連線的 IP(若無代理則為真實 IP)需按優先級解析,並過濾私有網段(10.x、172.16~31.x、192.168.x)避免偽造。
<?php
function getRealIp(): string {
$ip = false;
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
if ($ip) array_unshift($ips, $ip);
foreach ($ips as $candidate) {
// 過濾私有/保留網段
if (!preg_match('/^(10|172\.(1[6-9]|2[0-9]|3[0-1])|192\.168)\./', $candidate)) {
$ip = $candidate;
break;
}
}
}
return $ip ?: ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
}
?>
| CMS | 修改檔案 | 變數名 |
|---|---|---|
| Supesite / UCenter | include/main.inc.php | $_SGLOBAL['onlineip'] |
| Discuz! (X 系列) | source/class/discuz/discuz_application.php 或 config/config_global.php | $onlineip / $_G['clientip'] |
| 帝國 CMS | e/class/connect.php → egetip() | 返回值 |
| WordPress | wp-config.php 定義 $_SERVER['REMOTE_ADDR'] 或使用插件 | — |
| ThinkPHP / Laravel | 中介層 / Request::setTrustedProxies() | 框架自動處理 |
// source/module/member/member_register.php 約 200 行
// showmessage('register_invite_iperror'); // 註釋此行可暫時繞過
警告:關閉 IP 檢查會導致惡意註冊激增,請務必配合驗證碼、郵箱驗證、頻率限制等多重防護。
' ASP 經典
Function GetClientIP()
If CheckIP(Request.ServerVariables("HTTP_CLIENT_IP")) Then
GetClientIP = Request.ServerVariables("HTTP_CLIENT_IP")
Else
arr = Split(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ",")
If UBound(arr) >= 0 And CheckIP(Trim(arr(0))) Then
GetClientIP = Trim(arr(0))
Else
GetClientIP = Request.ServerVariables("REMOTE_ADDR")
End If
End If
End Function
Function CheckIP(ip)
CheckIP = ip Like "###.###.###.###" ' 簡易正則
End Function
// ASP.NET (C#)
public string GetClientIp() {
var ip = Request.Headers["X-Forwarded-For"]?.Split(',')[0].Trim();
if (IPAddress.TryParse(ip, out var addr) && !IsPrivate(addr))
return ip;
return Request.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "0.0.0.0";
}
bool IsPrivate(IPAddress ip) {
var bytes = ip.GetAddressBytes();
return bytes[0] == 10
|| (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)
|| (bytes[0] == 192 && bytes[1] == 168);
}