How To Get Remote IP Address in PHP

Here I am going to share information about How To Get Remote IP Address in PHP, you can use below function keep record of the user who logged into your website through his/her IP address and track that users.
how-to-get-user-ip-address-using-php

function getRemoteIPAddress() {
	$ip = $_SERVER['REMOTE_ADDR'];
	return $ip;
}




The above code will not work in case your client is behind proxy server. $_SERVER[‘REMOTE_ADDR’] may not actually contain real client IP addresses, as it will give you a proxy address for clients connected through a proxy,



There are several HTTP headers like X-Forwarded-For which may or may not be set by various proxies. The problem is that those are merely HTTP headers which can be set by anyone. There’s no guarantee about their content. “$_SERVER[‘REMOTE_ADDR’]” is the actual physical IP address that the web server received the connection from and that the response will be sent to. Anything else is just arbitrary and voluntary information. There’s only one scenario in which you can trust this information: you are controlling the proxy that sets this header. Meaning only if you know 100% where and how the header was set should you heed it for anything of importance.Having said that, here’s some sample code:

function getRealIPAddress()
{
	if (!empty($_SERVER['HTTP_CLIENT_IP']))   
	{
		$ip=$_SERVER['HTTP_CLIENT_IP'];
	}
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   
	{
		$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	}
	else
	{
		$ip=$_SERVER['REMOTE_ADDR'];
	}
	return $ip;
}

Using the above code has security implications. The client can set all HTTP header information (ie. $_SERVER[‘HTTP_…) to any arbitrary value it wants. As such it’s far more reliable to use $_SERVER[‘REMOTE_ADDR’], as this cannot be set by the user.

Posted in PHP