PHP: How to use .env file to store environment variables

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

In modern PHP development, managing application configuration and secrets safely and efficiently is fundamental. Utilizing a .env file for environment variables is a widely adopted practice designed to facilitate this aspect, keeping sensitive data out of the version control system. This tutorial will navigate through setting up and using .env files in PHP, offering an array of examples to suit developers at all levels.

What are environment variables?

Environment variables provide a way to influence the behavior of software on a system. They are dynamic-named values that can affect the way running processes will behave on a computer.These variables enable you to separate sensitive credentials or configuration details from your code, which increases security and flexibility.

To use .env files in PHP, a common library is the PHP package ‘vlucas/phpdotenv’. Here, we’ll explore this package and provide example code to utilize .env files in PHP applications.

Setting up .env in PHP

To begin, you’ll need to install the ‘vlucas/phpdotenv’ package using Composer:

composer require vlucas/phpdotenv

Once installed, you can create a .env file in the root directory of your PHP project. Ensure to add this file to your .gitignore to prevent potentially sensitive information from being exposed in your version control system.

In your .env file, you can then set environment variables as key-value pairs:

DB_HOST=localhost
DB_DATABASE=my_database
DB_USERNAME=my_username
DB_PASSWORD=my_password

Accessing these variables in your PHP code involves initializing the Dotenv library and calling the ‘load’ method. This should occur early in the application bootstrapping process, typically in your main ‘index.php’ file or config script:

use Dotenv\Dotenv;

require_once __DIR__ . '/vendor/autoload.php';

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

You’ll then be able to utilize environment variables by calling PHP’s ‘getenv’ function or accessing the ‘$_SERVER’ or ‘$_ENV’ superglobals:

$db_host = getenv('DB_HOST');
// or
$db_host = $_SERVER['DB_HOST'];

Managing Different Environments

Managing different configurations for multiple deployment contexts (development, staging, production) can be done by creating distinct .env files for each context, like .env.local or .env.production.

Advanced Usage

For more advanced scenarios, phpdotenv allows you to require certain variables to be defined, provide default values, or even cast variables to specific data types or convert values to Boolean. Here’s an example of how to require and cast variables:

$dotenv->required(['DB_HOST', 'DB_DATABASE', 'DB_USERNAME', 'DB_PASSWORD']);
$debug = filter_var(getenv('DEBUG'), FILTER_VALIDATE_BOOLEAN);

It’s also possible to overload environment variables, which can be valuable in specific scenarios such as running PHPUnit tests.

Security Considerations

Remember that even though .env files are not committed to version control, they must be protected at all costs. Always set proper file permissions, and be mindful about where and how you access the .env file in your code.

Best Practices

Using environment variables for credentials and configuration enables you to follow the 12-factor app methodology, contribute to a clearer codebase, and facilitate continuous deployment practices. Remember to keep your .env file simple, avoid storing it in public directories, and only access variables through secure means.

Conclusion

Utilizing .env files in PHP applications is an effective way to manage environment-specific configurations and sensitive credentials. With the popular ‘vlucas/phpdotenv’ package, integrating .env file handling is straightforward and can greatly benefit both development workflows and application security. Remember to always prioritize security by carefully managing access to the .env file and continuously revisiting your app’s configuration strategies to ensure best practices.