在PHP中检索用户正确IP地址的最准确方法是什么?
我知道有太多的$_SERVER变量头可用于IP地址检索。我想知道对于如何使用所述变量最准确地检索用户的真实IP地址(明知没有一种方法是完美的)是否有普遍的共识?
我花了一些时间试图找到一个深入的解决方案,并根据许多来源提出了以下代码。如果有人能在答案中戳出漏洞,或者对可能更准确的东西进行一些阐述,我会很高兴。
编辑包括来自@Alix的优化
/**
* Retrieves the best guess of the client's actual IP address.
* Takes into account numerous HTTP proxy headers due to variations
* in how different ISPs handle IP addresses in headers between hops.
*/
public function get_ip_address() {
// Check for shared internet/ISP IP
if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_CLIENT_IP']))
return $_SERVER['HTTP_CLIENT_IP'];
// Check for IPs passing through proxies
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// Check if multiple IP addresses exist in var
$iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach ($iplist as $ip) {
if ($this->validate_ip($ip))
return $ip;
}
}
}
if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_X_FORWARDED']))
return $_SERVER['HTTP_X_FORWARDED'];
if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
return $_SERVER['HTTP_FORWARDED_FOR'];
if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_FORWARDED']))
return $_SERVER['HTTP_FORWARDED'];
// Return unreliable IP address since all else failed
return $_SERVER['REMOTE_ADDR'];
}
/**
* Ensures an IP address is both a valid IP address and does not fall within
* a private network range.
*
* @access public
* @param string $ip
*/
public function validate_ip($ip) {
if (filter_var($ip, FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4 |
FILTER_FLAG_IPV6 |
FILTER_FLAG_NO_PRIV_RANGE |
FILTER_FLAG_NO_RES_RANGE) === false)
return false;
self::$ip = $ip;
return true;
}
警告词(更新)
REMOTE_ADDR
仍表示 IP 地址的最可靠来源。这里提到的其他变量可以很容易地被远程客户端欺骗。此解决方案的目的是尝试确定位于代理后面的客户端的 IP 地址。出于一般目的,您可以考虑将其与直接从中返回的 IP 地址结合使用并存储两者。$_SERVER
$_SERVER['REMOTE_ADDR']
对于99.9%的用户来说,这个解决方案将完全满足您的需求。它不会保护您免受0.1%的恶意用户通过注入自己的请求标头来滥用您的系统。如果依靠IP地址进行关键任务,请诉诸并且不要费心迎合代理背后的人。REMOTE_ADDR