4

In CLI mode getenv('HOSTNAME') returns HOSTNAME environment variable correctly, but when called in script returns FALSE.

Why? How can I get the HOSTNAME variable in script?

6 Answers 6

7

The HOSTNAME is not available in the environment used by Apache, though it usually IS available in the environment used by the CLI.

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')); 
Sign up to request clarification or add additional context in comments.

Comments

6

HOSTNAME is not a CGI environment variable, hence not present in normal PHP scripts.

But you can alternatively use

$hostname = `hostname`;     // exec backticks

Or read the system config file:

$hostname = file_get_contents("/etc/hostname");   // also only U*ix

But most PHP scripts should just use $_SERVER["SERVER_NAME"] or the client-requested $_SERVER["HTTP_HOST"]

2 Comments

Thanks for clearing this up for me. I think I'll go with SERVER_NAME instead.
/etc/hostname is very linuxy. Don't count on U*ix having it.
0

Your environment is likely cleaned in the webserver or php-fcgi/fpm start up script, so that sensitive information about the startup account is not leaked to the webserver.

Comments

0

I think you want HTTP_HOST which then is empty when you access it in CLI mode.

Comments

0

try something like this maybe?

function getHostName()
{
  //if we are in the shell return the env hostname
  if(array_key_exists('SHELL', $_ENV))
  {
     return getenv('HOSTNAME');
  }
  return $_SERVER['SERVER_NAME'];
}

Comments

0

There also exists an ENV variable you can access via <?php print_r($_ENV); ?>. But I get the same thing: cli has more variable than the server, but it must be configuration issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.