Best way to get hostname with php

Php

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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')); 

Solution 3 - Php

You could also use...

$hostname = getenv('HTTP_HOST');

Solution 4 - Php

I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

php_uname('n');

gethostname();

Solution 5 - Php

The accepted answer gethostname() may infact give you inaccurate value as in my case

gethostname()         = my-macbook-pro     (incorrect)
$_SERVER['host_name'] = mysite.git         (correct)

The value from gethostname() is obvsiously wrong. Be careful with it. Update as corrected by the comment

Host name gives you computer name, not website name, my bad. My result on local machine is

gethostname()         = my-macbook-pro     (which is my machine name)
$_SERVER['host_name'] = mysite.git         (which is my website name)

Solution 6 - Php

php_uname but I am not sure what hostname you want the hostname of the client or server.

plus you should use cookie based approach

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmattwegView Question on Stackoverflow
Solution 1 - PhpzombatView Answer on Stackoverflow
Solution 2 - PhpghbarrattView Answer on Stackoverflow
Solution 3 - PhpPedroView Answer on Stackoverflow
Solution 4 - PhpMike GraceView Answer on Stackoverflow
Solution 5 - PhpHammad KhanView Answer on Stackoverflow
Solution 6 - PhpRageZView Answer on Stackoverflow