Monday, September 12, 2022

Adding PHP Environment Variables with Lines in /etc/php/8.1/php-fpm/pool.d/www.conf

I finally found a clean enough way to inject PHP environment variables into my applications that doesn't completely pucker my parts where the sun does not shine-- in this case the app environment(dev, test, prod) coincidentally and hostname. The example is dripping in Debian/*buntu flavor, you have been warned.

As a "twofer", this is how you might set up the capsule for the Cartalyst Sentinel library in an implementation loaded from Composer, as an example of how to create and use the values.

Example variables to put into my www.conf file of my php-fpm config. For me this file lives under /etc/php/8.1/fpm/conf.d/www.conf . Just right at the bottom of the file, append your environment variable definitions right there at the end. I restart my php-fpm process with brad@hostname$sudo systemctl restart php8.1-fpm for lack of any reason to do otherwise.

env[environment] = 'prod'


env[sentinelDriver] = 'mysql'

env[sentinelHost] = 'hostname-that-might-be-localhost'

env[sentinelDatabase] = 'sentinel-database-name'

env[sentinelUsername] = 'sentinel-database-username'

env[sentinelPassword] = 'sentinel-database-password'

env[sentinelCharset] = 'utf8'

env[sentinelCollation] = 'utf8_unicode_ci'


And then where the rubber meets the road in your PHP files:


$capsule = new Capsule;


$capsule->addConnection([

    'driver'    => $_SERVER['sentinelDriver'];

    'host'      => $_SERVER['sentinelHost'];

    'database'  => $_SERVER['sentinelDatabase'];

    'username'  => $_SERVER['sentinelUsername'];

    'password'  => $_SERVER['sentinelPassword'];

    'charset'   => $_SERVER['sentinelCharset'];

    'collation' => $_SERVER['sentinelCollation'];

];

A word of caution. The php-fpm www.conf default for showing the system environment variables is:

clear_env = yes

However, you won't see that configuration setting. So, for me, the following default that I do see in every configuration of every system I have ever provisioned is correct:

;clear_env = no

I don't want my real system environment variables available via my application so far. Possible, yes. Desired functionality, no.

clear_env = no

Followers