Correct php code for seeing the IP Address of the Server

You can check your ip address for your machine by using the following code:

echo $_SERVER[‘REMOTE_ADDR’];

If you wanted to check whether the IP address got changed then try with the below statement.

echo $_SERVER[‘SERVER_ADDR’];

And, it was showing the new ip address. But below statement is still showing the old ip address.

echo file_get_contents(“whatismyip.com”)

So, If you would like to know whether $_SERVER[‘SERVER_ADDR’] is the correct way of knowing the IP address of the server.

Use the below function for finding actual IP address.
function getRealIpAddr()
{
if (!empty($_SERVER[‘HTTP_CLIENT_IP’])) //check ip from share internet
{
$ip=$_SERVER[‘HTTP_CLIENT_IP’];
}
elseif (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])) //to check ip is pass from proxy
{
$ip=$_SERVER[‘HTTP_X_FORWARDED_FOR’];
}
else
{
$ip=$_SERVER[‘REMOTE_ADDR’];
}
return $ip;
}

Posted in Php Tagged with: