Top 3 Dotenv PHP Libraries and a Quick Tutorial

Dotenv with PHP Blog Banner

What Is Dotenv? 

Dotenv is a module that loads environment variables from a .env file into the process.env object. This is useful for managing configuration settings that differ across development, testing, and production environments. With Dotenv, you can keep sensitive information like database credentials, API keys, and other configuration settings out of your codebase. This approach promotes better security and cleaner code, making it easier to handle various environment-specific settings without hardcoding them.

In PHP, Dotenv libraries serve the same purpose by offering a standardized way to manage environment variables. These libraries parse the .env file and make the variables available globally within your PHP application. This simplifies project setup, especially when multiple developers are involved or when deploying across different environments.

Benefits of Dotenv in PHP 

Here the primary benefits of using Dotenv files in PHP:

  • Simplified configuration management: Instead of scattering configuration settings across various files, you can consolidate them into a single .env file. This localized approach allows for easier management and modification of settings. When setting up a new environment, you only need to duplicate the .env file and adjust the values accordingly.
  • Consistency Across Environments: Dotenv helps maintain consistency across different development environments, which is crucial for smooth operations and reliable software deployments. This reduces discrepancies caused by environment-specific settings, making the development, testing, and deployment processes more predictable and stable.
  • Improved security: By moving sensitive information like API keys, database credentials, and other configuration settings to a .env file, you can exclude this file from version control systems like Git. This prevents sensitive data from being inadvertently shared with unauthorized users.

Important note: Storing credentials, and other sensitive data, in an .env file, is safer than saving them in your source code, but is also not secure. Anyone with access to your environment will be able to view and compromise the information. This is why it’s important to store sensitive data using a secrets management or configuration management system to encrypt and control access to sensitive information.

Top 3 Dotenv PHP Libraries 

1. phpdotenv

The phpdotenv library is a popular solution for managing environment variables in PHP applications. It allows you to load variables from a .env file into your environment, making them accessible throughout your PHP scripts. The library is easy to integrate and supports various features like variable expansion, allowing you to define one variable in terms of another. This flexibility makes phpdotenv a good choice for managing environment variables in PHP.

phpdotenv also includes validation features to ensure that required environment variables are defined and adhere to a specific format. This means you can catch configuration errors early in the development lifecycle, reducing the risk of deployment issues.

2. PHP-DotEnv

PHP-DotEnv is another lightweight library that simplifies the management of environment variables in PHP applications. It allows developers to load configuration values from a .env file into environment variables, making them accessible via getenv(), _ENV, and _SERVER.

PHP-DotEnv provides automatic type conversion for certain values. Boolean values are processed as true or false, quoted strings have their quotes removed, “null” is converted to the PHP null value, and numeric values are converted to integers or floats. Additionally, PHP-DotEnv allows for custom processors to handle specific types of values in the .env file, such as booleans, quoted strings, null values, and numbers.

3. DotEnvWriter

DotEnvWriter is another PHP library to simplify the management of environment variables in .env files. It allows you to programmatically add, update, or delete variables. By using DotEnvWriter, developers can ensure that environment-specific settings are easily maintained and updated without manually editing .env files.

The library is installable via Composer. To install, you simply run the command composer require mirazmac/dotenvwriter. Once installed, you can initialize DotEnvWriter by providing the path to your .env file. Setting environment variables is straightforward using the set method, and changes can be saved to the file with the write method.

DotEnvWriter offers several useful methods for managing environment variables. The set method allows you to add or update variables, while the delete method removes them. The hasChanged method checks if any variables have changed since the last write, and getContent retrieves the current content of the .env file. The write method saves changes to the .env file, with options to force writing or specify a different destination file.

Tips From the Expert

In my experience, here are tips that can help you better utilize Dotenv in PHP:

  1. Use environment variable validation extensively: Leverage the validation features of Dotenv to enforce strict checks on your environment variables. Ensure types, formats, and required values are validated to catch misconfigurations early and avoid runtime errors.
  2. Implement environment variable encryption: For added security, consider encrypting sensitive values within your .env file. Use a decryption mechanism in your application to handle these values securely.
  3. Monitor environment variable changes: Implement logging or monitoring for changes to environment variables in your application. This can help detect unauthorized modifications and enhance security auditing.
  4. Use hierarchical .env files Structure your .env files hierarchically to manage complex configurations. For example, use .env.development, .env.testing, and .env.production files, and load them conditionally based on the environment.

Use environment variable prefixes: To avoid collisions and enhance readability, prefix environment variables with the application name or a related context. For instance, use APP_DB_HOST instead of DB_HOST for clarity.

Ran Cohen photo
Ran Cohen
CTO & Co-Founder, Configu

Tutorial: Getting Started with the phpdotenv Library

This tutorial is adapted from the official phpdotenv documentation.

Prerequisites

Ensure Composer is installed on your system. You can use the following commands:

cd ~

curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php

sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer

Installation

You can install the PHP Dotenv library easily via Composer:

$ composer require vlucas/phpdotenv

Alternatively, you can manually add it to your composer.json file and run composer update.

Basic Usage

Create a .env File:
In the root directory of your project, create a .env file and add your configuration variables. Ensure this file is included in your .gitignore to keep sensitive data out of version control.

S3_BUCKET="dotenv"
SECRET_KEY="super_secret_key”

Create a .env.example File:
This file should contain all the required environment variables with either dummy values or blank placeholders. It helps developers understand which variables they need to set up.

S3_BUCKET="devbucket"
SECRET_KEY="abc123”

Load Environment Variables:
In your application, use the following code to load the environment variables from the .env file:

require 'vendor/autoload.php';
use Dotenv\Dotenv;
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
// Output the read environment variables
echo 'S3_BUCKET: ' . $_ENV['S3_BUCKET'] . "\n";
echo 'SECRET_KEY: ' . $_ENV['SECRET_KEY'] . "\n";

To handle the case where the .env file might not exist, you can use safeLoad:

require 'vendor/autoload.php';
use Dotenv\Dotenv;
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->safeLoad();
// Output the read environment variables
echo 'S3_BUCKET: ' . $_ENV['S3_BUCKET'] . "\n";
echo 'SECRET_KEY: ' . $_ENV['SECRET_KEY'] . "\n";

Access Environment Variables:
After loading the variables, you can access them using the $_ENV or $_SERVER super-globals:

$s3_bucket = $_ENV['S3_BUCKET'];
$secret_key = $_SERVER['SECRET_KEY'];

Use Custom Filenames:
If you prefer to use a different filename for your environment variables, you can specify it as the second parameter. In our case the name of the configuration file is myconfig.

require 'vendor/autoload.php';
use Dotenv\Dotenv;
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__, 'myconfig');
$dotenv->load();
// Output the read environment variables
echo 'S3_BUCKET: ' . $_ENV['S3_BUCKET'] . "\n";
echo 'SECRET_KEY: ' . $_ENV['SECRET_KEY'] . "\n";

Advanced Features

Requiring Variables:
Ensure that certain environment variables are set and not empty:

require 'vendor/autoload.php';
use Dotenv\Dotenv;
// Create a new Dotenv instance
$dotenv = Dotenv::createImmutable(__DIR__);
// Load the .env file
$dotenv->load();
$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);
$dotenv->required('DATABASE_DSN')->notEmpty();

Our .env looks like the following:

DB_HOST=localhost
DB_NAME=my_db
DB_USER=php_db_user
DB_PASS=abcd1234
DATABASE_DSN=

Variable Types and Allowed Values:
Validate that environment variables are of specific types or fall within a set of allowed values. In the following code, we deliberately introduced an error.

require 'vendor/autoload.php';
use Dotenv\Dotenv;
// Create a new Dotenv instance
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->required('FOO')->isInteger();
$dotenv->required('SESSION_STORE')->allowedValues(['Filesystem', 'Memcached']);

When you attempt to run this code, you should get an error as shown below:

Our .env looks like the following:

FOO=12A
SESSION_STORE=redis

Nesting Variables:
You can nest variables within other variables to reduce redundancy:

BASE_DIR="/var/webroot/project-root"
CACHE_DIR="${BASE_DIR}/cache"
TMP_DIR="${BASE_DIR}/tmp"

Immutability and Custom Repositories:
Control whether Dotenv is allowed to overwrite existing environment variables:

$dotenv = Dotenv\Dotenv::createMutable(__DIR__);
$dotenv->load();

When we use the createMutable method, it loads environment variables from the .env file and overwrites any existing environment variables already set.

Customize the repository configuration for more advanced use cases:

require 'vendor/autoload.php';

use Dotenv\Dotenv;
use Dotenv\Repository\RepositoryBuilder;
use Dotenv\Repository\Adapter\EnvConstAdapter;
use Dotenv\Repository\Adapter\PutenvAdapter;

$repository = Dotenv\Repository\RepositoryBuilder::createWithNoAdapters()
    ->addAdapter(Dotenv\Repository\Adapter\EnvConstAdapter::class)
    ->addWriter(Dotenv\Repository\Adapter\PutenvAdapter::class)
    ->immutable()
    ->make();

$dotenv = Dotenv\Dotenv::create($repository, __DIR__);
$dotenv->load();

// Output the read environment variables using $_ENV and getenv
echo 'S3_BUCKET (via $_ENV): ' . $_ENV['S3_BUCKET'] . "\n";
echo 'SECRET_KEY (via $_ENV): ' . $_ENV['SECRET_KEY'] . "\n";

Managing and Securely Storing Environment Variables with Configu

In light of the limitations of Dotenv libraries, you should consider a more robust alternative to managing environment variables. Configu is a configuration management platform comprised of two main components, the stand-alone Orchestrator, which is open source, and the Cloud, which is a SaaS solution:

Configu Orchestrator

As applications become more dynamic and distributed in microservices architectures, configurations are getting more fragmented. They are saved as raw text that is spread across multiple stores, databases, files, git repositories, and third-party tools (a typical company will have five to ten different stores).

The Configu Orchestrator, which is open-source software, is a powerful standalone tool designed to address this challenge by providing configuration orchestration along with Configuration-as-Code (CaC) approach.

Configu Cloud

Configu Cloud is the most innovative store purpose-built for configurations, including environment variables, secrets, and feature flags. It is built based on the Configu configuration-as-code (CaC) approach and can model configurations and wrap them with unique layers, providing collaboration capabilities, visibility into configuration workflows, and security and compliance standardization.

Unlike legacy tools, which treat configurations as unstructured data or key-value pairs, Configu is leading the way with a Configuration-as-Code approach. By modeling configurations, they are treated as first-class citizens in the developers’ code. This makes our solution more robust and reliable and also enables Configu to provide more capabilities, such as visualization, a testing framework, and security abilities.

Learn more about Configu

Related Content

Dotenv Rails: Managing Environments Variables in Ruby on Rails

Dotenv in React with react-dotenv Library: Basics & Quick Tutorial

Dotenv Webpack: The Basics and a Quick Tutorial

Dotenv Typescript: The Basics and a Quick Tutorial

Using npm dotenv Package to Manage Node.js Environment Variables

Using Py Dotenv (python-dotenv) Package to Manage Env Variables

Managing Environment Variables With dotenv

Try Configu for free
Painless end-to-end configuration management platform
Get Started for Free