Managing Environment Variables in PHP

Now I work with more programming languages, I start to miss features from other languages when I come “home” to PHP. One that I hadn’t seen in PHP before I saw it in other languages such as NodeJS (I think Ruby had the original implementation) was: a way to easily control setting your environment variables, particularly in development. In NodeJS the dotenv library is great for this; handily in PHP vlucas has already created phpdotenv so we are all set to apply these tricks to PHP applications!

Managing Environment Variables

The overall idea is that your code can read variables from a local text file rather than from the actual environment variables. This makes it easier to switch projects because you can write a file per project and not have to re-export environment variables (or wonder why the variables are wrong if you didn’t start a new shell when switching projects). Also since I often write code for other people to use, such as example applications or starter kits, the .env file provides a clear list of the values they need to set for the thing to work.

.env Config File

Usually I use two files:

  • .env is the file where the actual values will be read from. Put the file name into .gitignore so that you never commit your actual credentials/config to the git repository!
  • .env-example hold just the keys, not the values, that a user needs to set up the project. This makes an easy “copy this file and fill in the blanks” exercise to get things rolling.

Note that you probably need some switches for production where it actually reads the environment variables that the CI system sets, since you won’t be deploying a .env.

The .env file looks like this:

AWESOME_API_KEY=abc123
AWESOME_API_SECRET=abcdef0123456789

Once the values are there, you can teach your PHP application to use them.

PHPdotenv

First, we’ll need to add the phpdotenv package to our project, using Composer:

composer require vlucas/phpdotenv

Then, in your code add something like this to the top of index.php or wherever you do your setup (after require "vendor/autoload.php" is probably a good place!):

$dotenv = new DotenvDotenv(__DIR__);
$dotenv->load();

Then all your variables are available where PHP expects them, such as $_ENV['AWESOME_API_KEY'].

Using environment variables in development is as easy as using config files but is more in touch with the way we usually configure applications on the production environment. Environment variables are a very standard way to pass in context to an application – hence the name! They literally let the application know about the environment it is currently operating in.

Hopefully you might find this useful for your own applications – thanks Vance for building this excellent library :)

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.