9

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?

j0k
  • 22,600
  • 28
  • 79
  • 90
Josh
  • 161
  • 1
  • 2
  • 5

2 Answers2

18

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;
}
kolbyjack
  • 17,660
  • 5
  • 48
  • 35
  • 1
    Hi, thanks for your reply. Okay that allows me to inject into $_SERVER['SOMEENV'], but how may I provide something for $_ENV['SOMEENV'] ? – Josh Dec 18 '11 at 16:46
  • 1
    $_SERVER array entries are created by the webserver but $_ENV variables are imported from the environment under which PHP interpreter is running and many are provided by the shell under which PHP is running. In the case of Apache, the php interpreter is embedded into the Apache process but this is not the case with Nginx. IOW, It is possible to set $_ENV variables with Nginx and $_SERVER is as good as it gets. – Dayo Dec 18 '11 at 17:40
  • Isn't there a `env` directive in NGINX? – CMCDragonkai Apr 13 '17 at 03:52
  • Yes, but it only affects the environment of the nginx master and worker processes (https://nginx.org/en/docs/ngx_core_module.html#env). Since php doesn't run inside of nginx like it does work mod_php on apache, nginx can't actually affect php's environment. – kolbyjack Apr 13 '17 at 15:09
6

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.

shrikeh
  • 661
  • 9
  • 12
  • 1
    You can access variables declared into php-fpm conf file because getenv() searches both $_ENV and $_SERVER as said here: http://stackoverflow.com/questions/3780866/why-is-my-env-empty – lrepolho Jan 28 '15 at 20:38