How do I pass environment variables to PHP-FPM?

How to pass environment variables to PHP-FPM

On a Linux Web server with PHP-FPM, how do you make environment variables available to the PHP scripting engine? Find out in this tutorial!

On a Linux server, there are several ways of declaring environment variables, and each application can adopt a different behavior and manage environment variables in a certain way. For example, if we take the Apache2 Web server as an example, it relies on a : /etc/apache2/envvars.

In this example, we'll be using a Debian 12 server with PHP-FPM 8.2, but this applies to other environments.

1. Configure PHP-FPM

Connect to your web server where PHP-FPM is installed. Using a text editor (nano, vi, etc.), you'll need to edit PHP-FPM's "www.conf" configuration file. You'll find it here:

nano /etc/php/8.2/fpm/pool.d/www.conf

Look for the following line:

;clear_env = no
PHP-FPM - Environment variables

We can see that the clear_env "is commented out and its default value is ". yes" . This means that, by default, PHP-FPM prevents environment variables from being read, and in a way "resets" all environment variables. This means they cannot be read, whether via getenv(), $_ENV or $_SERVER.

This can prove troublesome in certain scenarios. For example, when you need to rely on an ODBC connector, as this prevents the reading of the variable LD_LIBRARY_PATH.

In this case, remove the ";" character at the beginning of the line and ensure that the option is set to "no".

clear_env = no

After saving the configuration file, restart PHP-FPM :

systemctl restart php8.2-fpm.service

Now all you have to do is test your new configuration!

If this doesn't work, go back to the "www.conf" file you edited earlier. Under the "clear_env" directive, declare your environment variable(s).

Here are a few examples of syntax (provided in the configuration file):

env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp

Save the file, restart PHP-FPM and test.

2. Conclusion

After reading this article from the tutorial box, you will be able toaccess environment variables on your Linux machine within PHP scripts run on your Web server using PHP-FPM !

Resources :

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *