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

roc*_*k3t 42 php apache environment-variables

我的系统是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,$_ENV,getenv()和不存在$GLOBALS.换句话说'没有加载到PHP'.

Pat*_*ser 59

我有完全相同的问题.要解决它,我只是/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
Run Code Online (Sandbox Code Playgroud)

内容/etc/apache2/envvars:

# Load all the system environment variables.
. /etc/environment
Run Code Online (Sandbox Code Playgroud)

现在,我可以在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>
Run Code Online (Sandbox Code Playgroud)

这是一个如何使用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";
?>
Run Code Online (Sandbox Code Playgroud)