PHP: Get the server’s IP address.

This is a short guide on how to get the current server’s IP address using PHP.

Fortunately, this is pretty easy to do, as PHP has made it easily accessible in the $_SERVER array.

Take a look at the following piece of code:

//Getting the IP address of the server.
$serverIp = $_SERVER['SERVER_ADDR'];

//Print it out.
echo 'This server\'s IP address is ' . $serverIp;

In the snippet above, we retrieved the server’s IP address by accessing the SERVER_ADDR element in the $_SERVER array.

It is important to note that this will probably be “::1” or “127.0.0.1” if you are running this code on your local machine.

This is because the server is on your localhost. Consequently, one of the “loopback” addresses will be shown.

Accessing the server’s IP address using PHP can be useful for debugging purposes. This is especially true when you are using multiple servers behind a load balancer.

In certain cases, one server may contain a bug that isn’t present on any of the other servers. That, or one server has been configured differently and is exhibiting strange behavior.

Be careful not to mix up SERVER_ADDR and REMOTE_ADDR.

Remember that SERVER_ADDR is the IP address of the server that is executing the code and that REMOTE_ADDR is the IP address of the client. i.e. The user, proxy or load balancer that is making a request to your server.

Notice: Undefined index: SERVER_ADDR.

On certain platforms, such as Windows IIS 7, you may have to use LOCAL_ADDR instead of SERVER_ADDR.

If your app is cross-platform, then you should use the following function instead:

/*
 * Cross-platform function that gets the IP
 * address of the server.
 */
function getServerIp(){
    if(isset($_SERVER['SERVER_ADDR'])){
        return $_SERVER['SERVER_ADDR'];
    }
    elseif(isset($_SERVER['LOCAL_ADDR'])){
        return $_SERVER['LOCAL_ADDR'];
    }
    else{
        return false;
    }
}

The function above will check to see if the SERVER_ADDR element exists in the $_SERVER array.

If that element does not exist, then it will check to see if LOCAL_ADDR can be found.

Finally, in the unlikely event that neither of these elements can be found, it returns a FALSE value. This way, you can at least avoid any nasty undefined index warnings.