Get a Visitors’ IP Address - Accurately!

One of the sites that I’m working on at the moment requires some IP-specific functionality, but in testing I realised that the standard $_SERVER['REMOTE_ADDR'] wasn’t being as accurate as I wanted.  Then I realised that this variable doesn’t take into consideration visitors accessing via a proxy server or any random proxy/caching stuff put in place by their ISP.

So, I put together this simple little function that returns the actual IP of any visitor…

function getRemoteIP() {
	if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) { 
		return $_SERVER['HTTP_CLIENT_IP'];
	} else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
		return $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
		return $_SERVER['REMOTE_ADDR'];
	}
 
}
 

This simple function can replace $_SERVER['REMOTE_ADDR'] in your code, and very simply checks to see if the HTTP_CLIENT_IP environmental variable is set, if so we use that.  If that’s not set, we check for HTTP_X_FORWARDED, and if that’s not set then we pass back the standard REMOTE_ADDR variable.

My understanding is that the HTTP_CLIENT_IP or HTTP_X_FORWARDED headers are set by proxy servers, sometimes at a visitors’ ISP, and contain the IP of the machine accessing the proxy server. The REMOTE_ADDR in these cases would be the IP of the proxy itself.

The order of these checks means that any accesses via a proxy, or similar setup, will result in the IP of the machine accessing the proxy server being returned.  If the machine isn’t requesting pages via a proxy, then the first two criteria aren’t matched and the standard REMOTE_ADDR should be accurate.
 

Bookmark or share this article:

  • Digg
  • del.icio.us
  • Facebook
  • Google
  • description
  • Reddit
  • StumbleUpon

Comments on Get a Visitors’ IP Address - Accurately!

There has been 1 comment left on this entry so far, why not contribute your own thoughts?

Leave a Reply

Andrew Gatenby Web Developer, Designer & Geek