$_SERVER['REMOTE_ADDR'] Does Not Work Always, How To Get Visitor’s Real IP Address In PHP?


When you are connected to internet from the internet connection, it is not always directly connected to internet gateway. It may be connected to host computer which will be controlling most of the clients computers and so on. In this architecture of network, visitors IP address is not the actual IP address from which he/she is connected to internet. In such cases, your PHP script using $_SERVER['REMOTE_ADDR'] will give you wrong IP address. You need to cross check the IP address from share connection, forwarded IP, proxy etc to filter out the real IP address from the visitors machine. You can solve this issue by using the following php function.

This function will give you the real IP address of the visitors visiting your site, so later you can track it or save it in your records, table etc.

function getRealIpAddr(){
	  if (!empty($_SERVER['HTTP_CLIENT_IP']))
	  //check ip from share internet
	  {
		$ip=$_SERVER['HTTP_CLIENT_IP'];
	  }
	  elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	  //to check ip is pass from proxy
	  {
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	  }
	  else
	  {
		$ip=$_SERVER['REMOTE_ADDR'];
	  }
	  return $ip;
}

Related posts:

About Sach

Sachin is a web application developer, technology blogger and web addict! He has over 6 years of web development experience and he writes tutorials primarily focused on LAMP, Ajax, Api's, jQuery etc. He is usability expert and he always likes to share his knowledge with people.

, ,

  • Ignacio Javier

    Tried and useful to capture real IP from scripts in these days of akaimatech proxies. Tested ok in sourceforge’s servers.

  • Ignacio Javier

    I forgot. Thanks for it :-) !!!!

  • Ignacio Javier

    And I clicked on your adds! Down with google pay per click, down with monopolism,

    Indignation!!!

    Lets fight for a pay per view!!!!

    • SachinKRaj

      Thanks a lot :)