PHP Get User IP Address

This function takes into account the possibility that your server might be behind a proxy. 

In the event that your server is behind a proxy, the traditional method of using $_SERVER['REMOTE_ADDR'] will simply return the Proxy's IP address (not the user).

This function first attempts to grab the user's IP from other server variables (which take proxies into account) before resorting to REMOTE_ADDR.
function getUserIP() {
	$userIP = '';
	
	if (isset($_SERVER['HTTP_ORIGINAL_IP']) && !empty($_SERVER['HTTP_ORIGINAL_IP']))
		$userIP = $_SERVER['HTTP_ORIGINAL_IP'];
	elseif (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']))
		$userIP = $_SERVER['HTTP_CLIENT_IP'];
	elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
		$userIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
	elseif (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
		$userIP = $_SERVER['REMOTE_ADDR'];	
	
	return $userIP;
}
Posted by
Snippet Viewed 595 times.

Share your PHP code snippets:

  • Get some recognition & link back to your site.

 

Submit | Browse

Most Recent php snippets

Most Viewed