0

I have 3 LAMP servers. Today I have noticed many of the following in the PHP error log:

[11-Feb-2010 10:58:03] PHP Notice:  Undefined index:  HOSTNAME in ...

Of course, this is happening in PHP when I do this:

echo $_ENV['HOSTNAME'];

When I run hostname from the command line I get the proper (expected) hostname, also when I do

php -r 'echo $_ENV["HOSTNAME"];'

I get the proper (expected) hostname as well. Hence I think it's an issue in my Apache config rather than PHP (which is why I'm posting on ServerFault rather than StackOverflow)...

Any ideas? Servers are running RHEL.

mmattax
  • 1,304
  • 7
  • 19
  • 30

2 Answers2

3

The $_ENV superglobal contains environmental variables, but Apache presents the $_SERVER array instead. From the manual

These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables.

This should work instead:

echo php_uname('n'); 

Or PHP 5.3

echo gethostname(); 

I can't get $_ENV['HOSTNAME'] from within an apache invoked PHP script (apache prefork RHEL)

http://php.net/manual/en/function.gethostname.php

Andy
  • 5,230
  • 1
  • 24
  • 34
0

The $_ENV array in PHP is set from the environment variables in the Apache process, which are copied from the environment of the process that starts the Apache daemon. So when it has worked, it was because $HOSTNAME was exported from the environment in the process that started Apache, and when it has not worked, it's because $HOSTNAME was not exported from that environment.

I don't have an RHEL machine handy to check where this should be added, but in whatever script starts Apache (assuming sh/bash), you need to either export the internal Bash variable HOSTNAME:

export HOSTNAME

Add that line before the actual Apache initialization, and it will ensure that variable shows up to PHP has $_ENV['HOSTNAME']. Or if for some reason HOSTNAME is not set by your shell by default:

export HOSTNAME=$(hostname -s)
daveadams
  • 1,279
  • 6
  • 12