How To Load Variables From .env File Using PHP

.env (dotenv) file is a good place to store secret information like Password, API key, etc. Since it keeps secret information separate from the code, you can share your code without revealing your secret information. In this tutorial you will learn how to load variables form .env file using PHP.

How to Define Environment Variables in a .env File

.env file allows you to put custom environment variables in key-value pairs. Here is an example –

DB_NAME="my_test_db"
DB_USER="root"
DB_PASS="pass@123"
PORT=3000
STATUS="development"

Load .env Variables in a PHP File

There is a PHP package called dotenv which we will use to load the custom environment variables from .env file to a PHP file.

So first, install this package via composer –

composer require vlucas/phpdotenv

After installing the package, here is a way to use this package to load environment variables.

<?php
require('./vendor/autoload.php');
# __DIR__ location of the .env file
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

Now the .env variables are available in the $_ENV and $_SERVER super-globals.

<?php
require('./vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

echo $_ENV['DB_NAME'];
echo $_SERVER['DB_USER'];
echo $_ENV['PORT'];
my_test_db
root
3000

Nesting Variables:

You can nest an environment variable within another by wrapping an existing environment variable in ${…}.

BASE_DIR="/var/webroot/project-root"
CACHE_DIR="${BASE_DIR}/cache"
TMP_DIR="${BASE_DIR}/tmp"
<?php
require('./vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
echo "Base => {$_ENV['BASE_DIR']}\n";
echo "Cache => {$_ENV['CACHE_DIR']}\n";
echo "Tmp => {$_ENV['TMP_DIR']}";
Base => /var/webroot/project-root
Cache => /var/webroot/project-root/cache
Tmp => /var/webroot/project-root/tmp

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy