Passing system environment variables to PHP-FPM when using NGINX

Sometimes it comes in handy to set system environment variables (env var from now on!) and get the PHP to use it for something. My tech stack is usually NGINX+PHP-FPM and if you already tried if you set a env var you probably found that it doesn’t appear on $_SERVER or in the getenv().

For this article I will be using a php file with this content:

By now you probably know how to set a env var on, let’s say, a UNIX system (I really don’t know how Windows work, so in this whole article I will assume you use a good operating system!). So it’s something like this:

$ export PHP_FOO=bar

Using the command line let’s run the previous file and check the result!

Our env var is there! Now let’s check when you make a HTTP request to that same file!

I removed some information that I don’t want you to see, but trust me, the PHP_FOO isn’t there! Here is how you can pass the env vars to PHP-FPM.

First find your PHP-FPM pool config file. Try /etc/php/7.0/fpm/pool.d/www.conf but yours could be in other place or have a different name.

Find this line and uncomment it (remove the ‘;’):

;clear_env = no

And finally add something like this:

env[“PHP_FOO”] = $PHP_FOO

Reload your php-fpm and refresh your env.php:

There it is! Our PHP_FOO env var ready to be used!

But as you can see this configuration change expose lot’s of other informations. Everything that is in the environment of the user that is running the PHP-FPM is exposed here. So use it wisely!

This article is essentially for me don’t crawl the internet every single time I need this! I’m using this technique to set the environment on Laravel. Setting a APP_ENV env var and during Laravel bootstrap read the .env.$APP_ENV file depending on which server (development, production, etc) the app is running!

Feel free to comment and suggest any better approach!