Adding .env file support to a legacy PHP project

Posted on 19th December 2018 - Takes 2 minutes to read


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.


open source PHP frameworks legacy dotenv-loader environment