PHP-DotEnv is a lightweight PHP library designed to simplify the management of environment variables in your PHP applications. It provides an elegant solution for loading configuration values from a .env
file into the environment variables accessible via getenv()
, $_ENV
, and $_SERVER
. This documentation aims to guide you through the installation, usage, and features of PHP-DotEnv.
To install PHP-DotEnv, you can use Composer, the dependency manager for PHP.
composer require phpdevcommunity/php-dotenv
- PHP version 7.4 or higher
Before using PHP-DotEnv, you need to define your environment variables in a .env
file. This file should be placed in the root directory of your project. Each line in the file should follow the KEY=VALUE
format.
APP_ENV=dev
DATABASE_DNS=mysql:host=localhost;dbname=test;
DATABASE_USER="root"
DATABASE_PASSWORD=root
MODULE_ENABLED=true
NUMBER_LITERAL=0
NULL_VALUE=null
After defining your environment variables, you can load them into your PHP application using PHP-DotEnv.
<?php
use PhpDevCommunity\DotEnv;
$absolutePathToEnvFile = __DIR__ . '/.env';
(new DotEnv($absolutePathToEnvFile))->load();
Once loaded, you can access the environment variables using PHP's getenv()
function.
/**
* Retrieve the value of DATABASE_DNS
*/
var_dump(getenv('DATABASE_DNS'));
PHP-DotEnv provides automatic type conversion for certain types of values:
- Booleans: Processed as
true
orfalse
. - Quoted Strings: Surrounding quotes are removed.
- Null Values: Converted to
null
. - Numeric Values: Converted to integers or floats.
PHP-DotEnv allows you to define custom processors to handle specific types of values in your .env
file. These processors enable you to control how values are parsed and converted.
The BooleanProcessor
converts boolean values specified in the .env
file to PHP boolean types (true
or false
).
MODULE_ENABLED=true
The QuotedProcessor
removes surrounding quotes from quoted strings in the .env
file.
DATABASE_USER="root"
The NullProcessor
converts the string "null" to the PHP null
value.
NULL_VALUE=null
The NumberProcessor
converts numeric values to integers or floats.
NUMBER_LITERAL=0
PHP-DotEnv offers a straightforward and efficient solution for managing environment variables in PHP applications. By providing automatic type conversion and customizable processors, it simplifies the process of loading and handling configuration values from .env
files. Whether you're working on a small project or a large-scale application, PHP-DotEnv can help streamline your development process and ensure smooth configuration management. Explore its features, integrate it into your projects, and experience the convenience it brings to your PHP development workflow.