Get the client IP address using PHP

Get the client IP address using PHP

In php $_SERVER is a super global variable witch holds three kinds of bunch information, Header, Paths and Script Location. $_SERVER variable holds the data in associative array format. So we can simply print all data of $_SERVER using the print_r() method.

Most of the developers/learners simply use $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables to get the visitor’s/client’s IP address which doesn’t always return the correct IP Address. If the IP is from the share internet then you should use $_SERVER['HTTP_CLIENT_IP'], if the IP is from the proxy the you should use $_SERVER['HTTP_X_FORWARDED_FOR'] and if the IP is from the remote address then you should use $_SERVER['REMOTE_ADDR'] etc.

So, Finally get the correct IP address of the visitors in two ways:

1. Using getenv() function: it returns the value of an environment variable.

	
  function get_visitor_ip() {
	$ip = '';
	if (getenv('HTTP_CLIENT_IP'))
	     $ip = getenv('HTTP_CLIENT_IP');
	else if(getenv('HTTP_X_FORWARDED_FOR'))
	     $ip = getenv('HTTP_X_FORWARDED_FOR');
	else if(getenv('HTTP_X_FORWARDED'))
	     $ip = getenv('HTTP_X_FORWARDED');
	else if(getenv('HTTP_FORWARDED_FOR'))
	     $ip = getenv('HTTP_FORWARDED_FOR');
	else if(getenv('HTTP_FORWARDED'))
	     $ip = getenv('HTTP_FORWARDED');
	else if(getenv('REMOTE_ADDR'))
	     $ip = getenv('REMOTE_ADDR');
	else
	     $ip = 'UNKNOWN IP ADDRESS';
	return $ip;
}
echo get_visitor_ip(); // Calling function

2. Using $_SERVER array variable:

function get_visitor_ip () {
    $ip = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ip = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ip = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ip = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = 'UNKNOWN IP ADDRESS';
    return $ip;
}
echo get_visitor_ip();// calling function