search
top

Get IP Address in PHP

Many times we need the IP Address of the User visiting our website in our Application.

I am listing here the method to get the User IP Address, hope it might be useful to many of you.

//function for getting IP
//start
function getuserip() 
{
		
    if (isset($_SERVER))
   {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
            return $_SERVER["HTTP_X_FORWARDED_FOR"];
       
        if (isset($_SERVER["HTTP_CLIENT_IP"]))
            return $_SERVER["HTTP_CLIENT_IP"];
		
	        return $_SERVER["REMOTE_ADDR"];
    }
		
	    if (getenv('HTTP_X_FORWARDED_FOR'))
	        return getenv('HTTP_X_FORWARDED_FOR');
			
	    if (getenv('HTTP_CLIENT_IP'))
	        return getenv('HTTP_CLIENT_IP');
		
		    return getenv('REMOTE_ADDR');
}
//end

echo $user_ip = getuserip(); //call to the function

4 Responses to “Get IP Address in PHP”

  1. Привет! This let’s the web server keep its default behavior of saving the session locally, leaving it up to the load balancer to get a client back to that server.

  2. Jamey Kirby says:

    This code is more complete:

    function get_ip_address()
    {
    $header_checks = array(
    ‘HTTP_CLIENT_IP’,
    ‘HTTP_PRAGMA’,
    ‘HTTP_XONNECTION’,
    ‘HTTP_CACHE_INFO’,
    ‘HTTP_XPROXY’,
    ‘HTTP_PROXY’,
    ‘HTTP_PROXY_CONNECTION’,
    ‘HTTP_VIA’,
    ‘HTTP_X_COMING_FROM’,
    ‘HTTP_COMING_FROM’,
    ‘HTTP_X_FORWARDED_FOR’,
    ‘HTTP_X_FORWARDED’,
    ‘HTTP_X_CLUSTER_CLIENT_IP’,
    ‘HTTP_FORWARDED_FOR’,
    ‘HTTP_FORWARDED’,
    ‘ZHTTP_CACHE_CONTROL’,
    ‘REMOTE_ADDR’
    );

    foreach ($header_checks as $key)
    if (array_key_exists($key, $_SERVER) === true)
    foreach (explode(‘,’, $_SERVER[$key]) as $ip)
    {
    $ip = trim($ip);
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
    return $ip;
    }
    }

  3. Interesting article, thanks for sharing it with us.

Leave a Reply

top