Friday, January 28, 2011

Detect server name in PHP

I have a number of instances behind a loadbalancer. Is it possible to detect the name of the machine (e.g. ec2-XXX-XX-XXX-XXX.compute-1.amazonaws.com) in PHP for debugging? I looked through phpinfo() and it doesn't seem to have any kind of machine specific information.

  • This should do it:

    http://php.net/manual/en/reserved.variables.server.php

    $myservername = $_SERVER['SERVER_NAME'];
    
    Louis W : $_SERVER['SERVER_NAME'] is set to the domain name of my website, not the machine name. Because these are load balanced cloud instances I am sure there is a lot of magic happening behind the scenes.
    From Force Flow
  • you'll have to use $host = system("hostname") or similar as it appears PHP won't provide that info directly.

    IP seems a little more involved. Depends on how they've got things set up but you can try

    $config = system("ifconfig | grep \"inet addr\"");
    preg_match("/(\d{1,3})(\.\d{1,3})/", $config, $matches);
    $ip_addr = $matches[1];
    
    Louis W : Hmmm. I think we are getting closer, but all machines are reporting 'p-aws-img-www-02' as the hostname.
    Louis W : Is there a way to get the machine's (not the domain's) ip address?
    From bemace

0 comments:

Post a Comment