我知道有许多$ _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(',', …Run Code Online (Sandbox Code Playgroud)