Best way to get hostname with php

php

Question

I have a php application that is installed on several servers and all of our developers laptops. I need a fast and reliable way to get the server's hostname or some other unique and reliable system identifier. Here's what we have thought of so far:

<? $hostname = (!empty($_ENV["HOSTNAME"])) ? $_ENV["HOSTNAME"] : env('HOSTNAME'); ?>

<? $hostname = gethostbyaddr($_SERVER['SERVER_ADDR']); ?>

<? $hostname = exec('hostname'); ?>

What do you think?

1
49
9/11/2009 4:52:02 AM

Accepted Answer

What about gethostname()?

Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.

40
9/11/2009 4:41:01 AM

For PHP >= 5.3.0 use this:

$hostname = gethostname();

For PHP < 5.3.0 but >= 4.2.0 use this:

$hostname = php_uname('n');

For PHP < 4.2.0 use this:

$hostname = getenv('HOSTNAME'); 
if(!$hostname) $hostname = trim(`hostname`); 
if(!$hostname) $hostname = exec('echo $HOSTNAME');
if(!$hostname) $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); 

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon