如何在运行 CLI 和 Apache2Handler 时将系统环境变量放入 PHP 中?

2022-08-30 11:04:14

我的系统是 Ubuntu,我已经在 中设置了我的环境变量。/etc/environment

如果我使用CLI运行PHP脚本 - 环境变量被识别。/etc/environment

但是,如果我通过(即apache2handler)执行PHP脚本,则完全相同的脚本会打印出NULL,这意味着不会加载环境变量。http://domain/test.php/etc/environment

我所做的修复是添加变量,这解决了问题。/etc/apache2/envvars

但这是两个不同的文件,然后必须保持同步。

如何使PHP / Apache加载并从(系统)识别环境变量?/etc/environment

编辑:为了澄清事情,当我说“未加载到PHP中”时,这意味着来自的变量未在 , 中设置,并且不存在于 .换句话说,“未加载到PHP中”。/etc/environment$_SERVER$_ENVgetenv()$GLOBALS


答案 1

我有完全相同的问题。为了解决这个问题,我只是在里面采购。/etc/environment/etc/apache2/envvars

内容:/etc/environment

export MY_PROJECT_PATH=/var/www/my-project
export MY_PROJECT_ENV=production
export MY_PROJECT_MAIL=support@my-project.com

内容:/etc/apache2/envvars

# Load all the system environment variables.
. /etc/environment

现在,我可以在Apache虚拟主机配置文件和PHP中使用这些变量。

以下是 Apache 虚拟主机的示例:

<VirtualHost *:80>
  ServerName my-project.com
  ServerAlias www.my-project.com
  ServerAdmin ${MY_PROJECT_MAIL}
  UseCanonicalName On

  DocumentRoot ${MY_PROJECT_PATH}/www

  # Error log.
  ErrorLog ${APACHE_LOG_DIR}/my-project.com_error.log
  LogLevel warn

  # Access log.
  <IfModule log_config_module>
    LogFormat "%h %l %u %t \"%m %>U%q\" %>s %b %D" clean_url_log_format
    CustomLog ${APACHE_LOG_DIR}/my-project.com_access.log clean_url_log_format
  </IfModule>

  # DocumentRoot directory
  <Directory ${MY_PROJECT_PATH}/www>
    # Disable .htaccess rules completely, for better performance.
    AllowOverride None
    Options FollowSymLinks Includes
    Order deny,allow
    Allow from All

    Include ${MY_PROJECT_PATH}/config/apache/inc.mime-types.conf
    Include ${MY_PROJECT_PATH}/config/apache/inc.cache-control.conf

    # Rewrite rules.
    <IfModule mod_rewrite.c>
      RewriteEngine on
      RewriteBase /

      # Include all the common rewrite rules (for http and https).
      Include ${MY_PROJECT_PATH}/config/apache/inc.rewriterules-shared.conf
    </IfModule>
  </Directory>
</VirtualHost>

这是如何使用PHP访问它们的一个例子:

<?php
header('Content-Type: text/plain; charset=utf-8');
print getenv('MY_PROJECT_PATH') . "\n" .
      getenv('MY_PROJECT_ENV') . "\n" .
      getenv('MY_PROJECT_MAIL') . "\n";
?>

答案 2

在 ubuntu 上,PHP 对常规和 CLI 进程使用不同的 ini 文件。

应该很少有像 、 或 这样的 ini 文件。打开相关的INI文件并更改/etc/php5/cli/php.ini/etc/php5/fpm/php.ini/etc/php5/php.ini

variables_order = "GPCS"

行到

variables_order = "EGPCS".

之后,您将获得在使用 $_ENV['varname'] 之前设置的环境变量。

来自 php.ini 关于 :variables_order

Abbreviations for the following respective super globals: GET, POST, COOKIE,
ENV and SERVER. There is a performance penalty paid for the registration of
these arrays and because ENV is not as commonly used as the others, ENV is
is not recommended on productions servers. You can still get access to
the environment variables through getenv() should you need to.

所以你可以尝试使用getenv()而不是$_ENV[]。


推荐