Adding .env file support to a legacy PHP project

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 file in the root of your project.

Most modern frameworks, such as Laravel and Symfony, come with built in support for a 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, . This package provides very simple, automatic file support.

To install the 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 in any file you wish to access your file variables from.

You can now create a file in the root of your project, alongside your 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 readme on GitHub.

🖥️ Full stack developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store