我知道有很多$ _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地址的最可靠来源。$_SERVER
远程客户端可以很容易地欺骗这里提到的其他变量。该解决方案的目的是尝试确定位于代理后面的客户端的IP地址。为了您的一般目的,您可以考虑将其与直接从$_SERVER['REMOTE_ADDR']
两者存储并返回的IP地址结合使用。
对于99.9%的用户,此解决方案将完全满足您的需求。它不会通过注入自己的请求标头来保护您免受0.1%希望滥用系统的恶意用户的侵害。如果依靠IP地址执行某些关键任务,请诉诸于REMOTE_ADDR
代理代理,而不必理会这些代理。