.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.
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
Now you will learn how to load the custom environment variables from .env file to a PHP file. Let’s see –
To do this we will use the PHP dotenv package which you can easily install through the 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
PHP dotenv provides various features, for this you can read the official docs. Here is an example –
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