This may not typically apply to connections from localhost but you should take proxies into account. If the remote end is using a HTTP proxy, $_SERVER['REMOTE_ADDR']
will contain the IP address of that proxy rather than the IP address of the client itself.
However, if it is a proxy which has privacy settings disabled, then you may have a chance to obtain client IP using the following snippet:
// will be set by the proxy if no privacy is enabled:
if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if(isset($_SERVER['REMOTE_ADDR'])) {
return $_SERVER['REMOTE_ADDR'];
}
But if your client is using a HTTP proxy with privacy enabled, then you won't have a chance to get the clients IP.
Security Hint (thanks @deceze) Note that if you rely on the HTTP_X_FORWARDED_FOR
header, it will be easy for attackers to spoof their IP. Although this is possible using other techniques as well, it will be very easy using the HTTP_X_FORWARDED_FOR
header. You have been warned. But anyway an web application should never use IP information for security, therefore it's just a side-note