af83

Get remote ip address in PHP even when the user is behind a proxy

If you want to log what a user is doing, or have any other reason to get his ip using HTTP_CLIENT_IP to get the remote user IP is not at all enough, if the client is connecting through a proxy (for an example your site is configured behind an apache_mod_proxy) you should also test for HTTP_X_FORWARDED_FOR and fall back on REMOTE_ADDR or you might always be getting the proxie's IP.

 function getIP() {
$ip;

if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
else $ip = "UNKNOWN";

return $ip;

}

blog comments powered by Disqus