一尘不染

如何在运行CLI和Apache2Handler时将系统环境变量转换为PHP?

php

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

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

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

我所做的修复是在其中添加变量/etc/apache2/envvars,从而解决了该问题。

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

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

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


阅读 337

收藏
2020-05-29

共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 Virtual Host配置文件和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";
?>
2020-05-29