PHP $_SERVER[‘SERVER_ADDR’] variable always returns 127.0.0.1

Tom picture Tom · Jul 8, 2010 · Viewed 10k times · Source

We have multiple load-balanced webserver machines running the same PHP webapp (LAMP) and I'd like to run slightly different code on each server (for testing purposes). I was hoping to use the $_SERVER['SERVER_ADDR'] super global to do something like this:

if ($_SERVER['SERVER_ADDR'] == 'XXX.XXX.XXX.XXX') {
  echo "Do one thing";
} elseif ($_SERVER['SERVER_ADDR'] == 'YYY.YYY.YYY.YYY') {
  echo "Do something else";
}

Unfortunately, this doesn't work because both machines are setting $_SERVER['SERVER_ADDR'] to '127.0.0.1'. How can I configure them so that $_SERVER['SERVER_ADDR'] is set to their public IP address?

I'm guessing the issue may be something to do with /etc/hosts so for refererence it currently looks like this:

127.0.0.1       localhost.localdomain localhost
::1             localhost6.localdomain6 localhost6
XXX.XX.XX.XX    blahblah

Update...

Oops! I neglected to consider the nginx reverse proxy in front of the web servers. All the traffic to those web servers arrives from nginx due to the following line in the nginx conf:

location / {
    root                  /var/www/staging/current;
    proxy_pass            http://localhost:8880;
}

Answer

Kieran Allen picture Kieran Allen · Jul 9, 2010

Surely it's as simple as

$ip = getHostByName(php_uname('n')); 
echo $ip;