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
.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
$dotenv = new Symfony\Component\Dotenv\Dotenv(); $dotenv->load(__DIR__ . '/.env');
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.
As mentioned earlier, you will need to fetch the environment variables through
$_ENV rather than
$siteName = $_ENV['SITE_NAME']);
First published: 18th September 2020