如何让 PHP 能够读取系统环境变量


How to get PHP to be able to read system environment variables

我在 Centos 上使用 PHP 作为 PHP-FPM。我正在尝试遵循将设置存储在环境变量中的 http://12factor.net/准则。

我在/etc/profile.d 中创建了一个文件,用于设置我想要的环境变量,当通过 Bash 在 CLI 中测试时,即运行 bash 脚本时,会出现环境变量:

echo $SOME_SERVER_SETTING

显示正确的输出。

我已将clear_env设置设置为 false,variables_order设置为 EGPCS ,但是,我设置的变量在 PHP 中没有显示getenv('SOME_SERVER_SETTING')或执行var_dump($_ENV)

还需要设置什么其他设置来允许 PHP-FPM 接收所有服务器环境变量,特别是那些通过 Centos 上的/etc/profiles.d 中的 shell 脚本设置的变量?

在 Centos 7 上使用 Systemd 服务和 PHP 5.6.4 进行测试

打开

/etc/php.ini

找到

variables_order = "GPCS"

替换为

variables_order = "EGPCS"
# http://php.net/manual/en/ini.core.php#ini.variables-order

打开

/etc/php-fpm.d/www.conf (maybe /etc/php5/fpm/pool.d/www.conf)
(do not confuse with /etc/php-fpm.conf)

查找是否存在

clear_env = yes

替换或添加

clear_env = no
# http://php.net/manual/en/install.fpm.configuration.php

打开

/etc/environment

#any variables you need, for example:
MY_VAR=1234

在外壳中运行以进行检查

source /etc/environment
echo $MY_VAR # 1234

在壳牌中运行

ln -fs /etc/environment /etc/sysconfig/php-fpm
systemctl daemon-reload && service php-fpm restart

。测试

打开

index.php # in your project folder, running with php-fpm

var_dump(getenv('MY_VAR'), $_ENV['MY_VAR']);exit;

在浏览器中运行

http://mylink.to.project/index.php   
string(4) "1234"
string(4) "1234"

享受!

安全原因 :-)

请参阅/etc/php5/fpm/pool.d/www.conf(debian 位置,在 CentOS 上可能有所不同)

; Clear environment in FPM workers
; Prevents arbitrary environment variables from reaching FPM worker processes
; by clearing the environment in workers before env vars specified in this
; pool configuration are added.
; Setting to "no" will make all environment variables available to PHP code
; via getenv(), $_ENV and $_SERVER.
; Default Value: yes
;clear_env = no 
; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

FastCGI设置中的环境变量由FPM进程的客户端设置为输入,例如NginX。它们作为标头发送到 FastCGI 服务器,该服务器解释它们并相应地设置它们,以便您使用 getenv 读出。

如果您实际上使用的是NginX,请查找fastcgi_param指令。您还可以在 php5-fpm 的池配置中设置环境变量,具体取决于您的用例。

您需要从正确的位置读取环境变量。PHP 为此创建了一个超级全局变量: $_ENV 因此,您可以通过访问该变量中的某个元素来访问单个变量,该变量包含一个数组:echo $_ENV['SOME_SERVER_SETTING'];

我不知道为什么你上面的例子应该在 CLI 上工作。超级全局变量是记录的位置并起作用。

您的问题可能是没有为 http 服务器进程设置变量。通常,像 /etc/profile.d 中的脚本在登录时执行。因此,当用户在系统内创建会话时。但是对于作为系统服务器启动的 http 服务器,这永远不会发生。不执行登录,不执行配置文件脚本,不设置环境变量。

要解决这个问题,您可以

  • 在服务的启动脚本中设置环境变量
  • 在主机配置或.htaccess样式文件中设置变量
  • 自动预置设置变量的脚本