In CLI mode getenv('HOSTNAME')
r开发者_运维百科eturns 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.
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'));
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"]
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.
I think you want HTTP_HOST
which then is empty when you access it in CLI mode.
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'];
}
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.
精彩评论