PHP getenv ('HOSTNAME')

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

Why? How to get the HOSTNAME variable in a script?

+4
source share
6 answers

HOSTNAME not a CGI environment variable, therefore it is not present in regular PHP scripts.

But you can also use

 $hostname = `hostname`; // exec backticks 

Or read the system configuration file:

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

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

+6
source

HOSTNAME is not available in the environment used by Apache, although it is usually 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')); 
+6
source

Your environment is most likely cleaned up on the web server or php-fcgi / fpm when you run the script, so that confidential startup account information will not leak on the web server.

0
source

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

0
source

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']; } 
0
source

There is also an ENV variable with which you can access via <?php print_r($_ENV); ?> <?php print_r($_ENV); ?> . But I get the same thing: cli has more variables than the server, but this should be a configuration problem.

0
source

All Articles