Last updated on December 2, 2022
Today’s Post is about Getting Visitor’s Real IP Address Using PHP, you can get visitor IP with the help of server Environment Variables in PHP.
we can easily get the visitor’s IP address with $_SERVER['REMOTE_ADDR']
or $_SERVER['REMOTE_HOST']
Variables.
$_SERVER[‘REMOTE_ADDR’] is the only reliable IP address you’ll get – it’s extracted directly from the TCP stack and is where the current connection was established from. This means if the user is connecting via a proxy, you’ll get the proxy’s address, not the user’s.
So we can’t trust the result of the above variables, So In order to get the real correct IP address we have to use some other server variables.
function get_client_ip() {
if ($_SERVER['HTTP_CLIENT_IP'])
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if($_SERVER['HTTP_X_FORWARDED_FOR'])
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if($_SERVER['HTTP_X_FORWARDED'])
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if($_SERVER['HTTP_FORWARDED_FOR'])
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if($_SERVER['HTTP_FORWARDED'])
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if($_SERVER['REMOTE_ADDR'])
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
Note: HTTP_X_FORWARDED_FOR sometimes returns an internal or local IP address, which is not usually useful. Also, it would return a comma-separated list if it was forwarded from multiple ip addresses.
$_SERVER is an array contains server variables created by the web server.