Tag Archives: IP Address

Most accurate way to retrieve a user’s correct IP address in PHP

Sometimes it is required to determine cilent’s IP address in PHP applications. It is straight forward to get it from REMOTE_ADDR headers. However, it becomes tricky if there are proxies in-between.

Some application frameworks like Symfony has built-in method to get it. However, if you need to determine the IP address on your own, here is the the solution:

function get_ip_address(){
	$ipHeaders = array(
        'HTTP_CLIENT_IP', 
        'HTTP_X_FORWARDED_FOR', 
        'HTTP_X_FORWARDED', 
        'HTTP_X_CLUSTER_CLIENT_IP', 
        'HTTP_FORWARDED_FOR', 
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
	);
    foreach ($ipHeaders as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                // just to be safe
                $ip = trim($ip); 
                //filter the ip before returning
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

WARNING: REMOTE_ADDR still represents the most reliable source of an IP address. The other $_SERVER variables can be spoofed by a remote client very easily.

Ref: Stakeoverflow