Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP Dotenv


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.


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:


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');


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")  


Last updated: 18th September 2020
First published: 18th September 2020