Setting Enviroment Variables for PHP-FPM with Apache

Once in a while you may want to be able to pass information from the apache server to the php-fpm process, a way of doing it is by using environment variables, you can set them either in .htaccess files or in your virtual host configuration files.
 
You can set one variable per line as the following in your file of choice:

SetEnv VARIABLE_NAME "VARIABLE_VALUE"

 

When you set a variable this way you can read the values in your PHP script with the getenv function

$var = getenv("VARIABLE_NAME");

 
One nice use case is storing the database connection information on your virtual host file.

<VirtualHost *:80>
    ...
    ServerAdmin [email protected]
    Servername example.com
    SetEnv db_User "USERNAME"
    SetEnv db_Database "DATABASENAME"
    SetEnv db_Password "SECRET1337PASSWORD"
    SetEnv db_Host "HOSTOFTHEDATABASE"
    SetEnv db_Port "3306 FOR MYSQL"
    ...
</VirtualHost>

 
After restarting apache/reloading your configuration

$config["user"]= getenv("db_User");
$config["password"] = getenv("db_Password");
$config["name"] = getenv("db_Database");
$config["host"] = getenv("db_Host");
$config["port"] = getenv("db_Port");

Sources:

https://httpd.apache.org/docs/current/env.html
https://stackoverflow.com/questions/44170807/php-getenv-is-able-to-read-system-environment-variable
https://stackoverflow.com/questions/2378871/set-application-env-via-virtual-host-config-and-read-this-in-php