Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP Dotenv

PHP

It seems there is a Dotenv for every language, but this tutorial focuses on PHP. Dotenv focuses on loading variables from a .env (hence the name) file.

Steps

Include the package into your codebase if you haven't already:

composer require symfony/dotenv

Create a .env file if you havent got one already:

HELLO="WORLD"

You can load the .env variables with the following snippet of code in php (assuming you have already included your /vendor/autoload.php).

$dotenv = new Symfony\Component\Dotenv\Dotenv();
$dotenv->load(__DIR__ . '/.env');

Caveats

Only $_ENV Not getenv()

Whilst working on a project using Nginx instead of Apache (I need to check if this is the case with Apache), I noticed that I was only able to get the variables by using the $_ENV superglobal, and not through the getenv function.

If Variables Already In Environment

If you already have environment variables set with the same name (e.g. the output of running env in BASH), this will not set them, resulting in nothing being set in $_ENV (which is really annoying). To get around this, use the overload method like so:

$dotenv = new Symfony\Component\Dotenv\Dotenv();
$dotenv->overload(__DIR__ . '/.env');

Arrays Don't Work

Having the following in your .env file won't result in the variable being loaded as an array in PHP.

MY_ARRAY=("item1" "item2")  

Retrieving Variables

As mentioned earlier, you will need to fetch the environment variables through $_ENV rather than getenv(). E.g.

$siteName = $_ENV['SITE_NAME']);

References

Last updated: 15th November 2021
First published: 18th September 2020