Adding .env file support to a legacy PHP project

Jordan Hall
2 min readApr 9, 2021

--

Photo by Stephen Crowley on Unsplash

It’s a modern day standard that all web applications store their platform specific configuration in environment variables. In the PHP world, this usually mean a .env file in the root of your project.

Most modern frameworks, such as Laravel and Symfony, come with built in support for a .env file. For older projects, which may have an outdated framework, or perhaps no framework, there may be no support at all. In some cases, you might simply prefer to use a more standard environment file over the way in which configuration is currently provided by your project.

An Easy Solution

As part of upgrading a very old web application to a more modern architecture, I created an open source package, dotenv-loader. This package provides very simple, automatic .env file support.

To install the dotenv-loader package, simply run the following Composer command from the root of your project.

composer require DivineOmega/dotenv-loader

If your project or its framework already uses Composer, then you’re done. If not, make sure you include vendor/autoload.php in any file you wish to access your .env file variables from.

You can now create a .env file in the root of your project, alongside your composer.json file and populate it as follows.

MICE_QUANTITY=three
MICE_STATUS=blind
MICE_SPEED=run
CUTTING_TOOL="carving knife"

You can then easily access these variables from within your PHP scripts. Here’s a example.

require 'vendor/autoload.php';echo ucfirst(getenv('MICE_QUANTITY')).' '.getenv('MICE_STATUS').' mice. ';
echo ucfirst(getenv('MICE_QUANTITY')).' '.getenv('MICE_STATUS').' mice. ';
echo '<br/>';echo 'See how they '.getenv('MICE_SPEED').'. ';
echo 'See how they '.getenv('MICE_SPEED').'. ';
echo '<br/>';echo 'They all ran after the farmer\'s wife,';echo '<br/>';echo 'Who cut off their tails with a '.getenv('CUTTING_TOOL').',';echo '<br/>';echo 'Did you ever see such a sight in your life,';echo '<br/>';echo 'As '.getenv('MICE_QUANTITY').' '.getenv('MICE_STATUS').' mice?';echo '<br/>';

Poor mice.

For more information about this package and additional documentation, see the dotenv-loader readme on GitHub.

--

--

Jordan Hall
Jordan Hall

No responses yet