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?
The HOSTNAME is not available in the environment used by Apache, though it usually IS available in the environment used by the CLI.
$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'));
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"]