How can I identify the server IP address in PHP?
The previous answers all give $_SERVER['SERVER_ADDR']. This will not work on some IIS installations. If you want this to work on IIS, then use the following:
$server_ip = gethostbyname($_SERVER['SERVER_NAME']);
Like this:
$_SERVER['SERVER_ADDR'];
Neither of the most up-voted answers will reliably return the server's public address. Generally $_SERVER['SERVER_ADDR']
will be correct, but if you're accessing the server via a VPN it will likely return the internal network address rather than a public address, and even when not on the same network some configurations will will simply be blank or have some other specified value.
Likewise, there are scenarios where $host= gethostname(); $ip = gethostbyname($host);
won't return the correct values because it's relying on on both DNS (either internally configured or external records) and the server's hostname settings to extrapolate the server's IP address. Both of these steps are potentially faulty. For instance, if the hostname of the server is formatted like a domain name (i.e. HOSTNAME=yahoo.com
) then (at least on my php5.4/Centos6 setup) gethostbyname
will skip straight to finding Yahoo.com's address rather than the local server's.
Furthermore, because gethostbyname
falls back on public DNS records a testing server with unpublished or incorrect public DNS records (for instance, you're accessing the server by localhost
or IP address, or if you're overriding public DNS using your local hosts
file) then you'll get back either no IP address (it will just return the hostname) or even worse it will return the wrong address specified in the public DNS records if one exists or if there's a wildcard for the domain.
Depending on the situation, you can also try a third approach by doing something like this:
$external_ip = exec('curl http://ipecho.net/plain; echo');
This has its own flaws (relies on a specific third-party site, and there could be network settings that route outbound connections through a different host or proxy) and like gethostbyname
it can be slow. I'm honestly not sure which approach will be correct most often, but the lesson to take to heart is that specific scenarios/configurations will result in incorrect outputs for all of these approaches... so if possible verify that the approach you're using is returning the values you expect.
Check the $_SERVER array
echo $_SERVER['SERVER_ADDR'];
$serverIP = $_SERVER["SERVER_ADDR"];
echo "Server IP is: <b>{$serverIP}</b>";
You may have to use $HTTP_SERVER_VARS['server_ADDR']
if you are not getting anything from above answers and if you are using older version of PHP