Linux PHP getenv('HOSTNAME')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6070810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:09:54  来源:igfitidea点击:

PHP getenv('HOSTNAME')

phplinuxenvironment-variables

提问by Dziamid

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

在 CLI 模式下正确getenv('HOSTNAME')返回HOSTNAME环境变量,但在脚本中调用时返回FALSE.

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

为什么?如何在脚本中获取 HOSTNAME 变量?

采纳答案by mario

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

HOSTNAME不是 CGI 环境变量,因此不存在于普通 PHP 脚本中。

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"]

但是大多数 PHP 脚本应该只使用$_SERVER["SERVER_NAME"]或客户端请求的$_SERVER["HTTP_HOST"]

回答by Mel

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.

您的环境可能在 webserver 或 php-fcgi/fpm 启动脚本中被清理,因此有关启动帐户的敏感信息不会泄漏到 web 服务器。

回答by powtac

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

我认为HTTP_HOST当您在 CLI 模式下访问它时,您希望它是空的。

回答by SnatchFrigate

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

回答by Aif

There also exists an ENVvariable 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.

还存在一个ENV您可以通过访问的变量<?php print_r($_ENV); ?>。但我得到了同样的东西:cli 比服务器有更多的变量,但它一定是配置问题。

回答by ghbarratt

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

HOSTNAME 在 Apache 使用的环境中不可用,但它通常在 CLI 使用的环境中可用。

For PHP >= 5.3.0 use this:

对于PHP >= 5.3.0 使用这个

$hostname = gethostname();

$hostname = gethostname();

For PHP < 5.3.0 but >= 4.2.0 use this:

对于PHP < 5.3.0 但 >= 4.2.0 使用这个

$hostname = php_uname('n');

$hostname = php_uname('n');

For PHP < 4.2.0 use this:

对于 PHP < 4.2.0 使用这个:

$hostname = getenv('HOSTNAME'); 
if(!$hostname) $hostname = trim(`hostname`); 
if(!$hostname) $hostname = exec('echo $HOSTNAME');
if(!$hostname) $hostname = preg_replace('#^\w+\s+(\w+).*$#', '', exec('uname -a'));