Setting $_ENV (fka $HTTP_ENV_VARS) with nginx/php-

2019-03-19 16:07发布

问题:

What is the equivalent of setenv in a apache environment? With apache I am able to for example set the env "SOMEENV" and access it in php via $_ENV['SOMEENV'] - but I have no idea how to do it with nginx+php-fpm.

I initially thought that I just have to set ENV[SOMENEV]=test in the config of my php-fpm pool, but var_dump($_ENV) still returns nothing.

Any hints?

回答1:

nginx doesn't have a way of affecting php's environment, since it doesn't embed the php interpreter into its process. It passes parameters to php through fastcgi_param directives. You can just add one where you set the rest of your params and access it via $_SERVER:

location ~ \.php$ {
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $request_filename;
  fastcgi_param SOMEENV test;
  fastcgi_pass php;
}


回答2:

Be aware that the availability of $_ENV variables depends on the setting of variables_order in the php.ini used by php-fpm. The default is EGPCS, where E is environment, however on Ubuntu 12.04 I found it was GPCS. The php.ini itself carries a warning regarding $_ENV:

; This directive determines which super global arrays are registered when PHP
; starts up. G,P,C,E & S are 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 not recommended on productions servers.

It recommends using getenv() which is always available. I found that variables I set in the FPM pool could be retrieved this way.