sugiphp / dotenv
Loads environment variables from a .env file into $_ENV and getenv().
Requires
- php: >=8.3
Requires (Dev)
- phpunit/phpunit: ^10.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-09-18 13:12:07 UTC
README
A minimal PHP library for loading environment variables from a .env file. Values are set into $_ENV and made available through PHP's getenv(), so the rest of your application can read configuration without caring where it came from.
Requirements
- PHP >= 8.3
Installation
composer require sugiphp/dotenv
Usage
Create a .env file in your project (commonly in the project root, next to composer.json):
DB_HOST=localhost
DB_NAME=my_database
DB_USER=root
DB_PASS="a secret with spaces"
Load it as early as possible in your bootstrap script:
<?php use SugiPHP\DotEnv\DotEnv; require __DIR__ . '/vendor/autoload.php'; (new DotEnv(__DIR__))->load(); echo getenv('DB_HOST'); // "localhost" echo $_ENV['DB_NAME']; // "my_database"
DotEnv throws a RuntimeException if the file cannot be found or read, so wrap load() in a try/catch if a missing .env file is not fatal for your application.
If putenv() and/or getenv() are disabled (e.g. via disable_functions on hardened hosting), load() degrades gracefully instead of failing: it still populates $_ENV, but skips whichever of the two functions is unavailable. In that case:
- If
putenv()is disabled, values are only available via$_ENV, notgetenv(). - If
getenv()is disabled,load()can no longer detect real environment variables set outside of PHP's$_ENV, so the "don't overwrite existing variables" guarantee only covers$_ENVin that case.
Custom file name
By default the library looks for .env in the given directory. Pass a second argument to use a different file, e.g. to load environment-specific configuration:
(new DotEnv(__DIR__, '.env.testing'))->load();
.env file format
- Each variable is defined on its own line as
KEY=value. - Blank lines are ignored.
- Lines starting with
#are treated as comments and ignored. - Leading/trailing whitespace around both the key and the value is trimmed.
- Values may be wrapped in single or double quotes; the surrounding quotes are stripped. Unmatched quotes are kept as part of the value.
- Only the first
=on a line is treated as the separator, so values containing=(e.g. connection strings) are preserved in full. - Variables that already exist in the environment (checked via both
$_ENVandgetenv()) are not overwritten, so real environment variables always take precedence over the.envfile. - If the same key is defined more than once within the same
.envfile, the last occurrence wins.
Example:
# Database
DB_DSN=pgsql:dbname=app;host=localhost
DB_PASS='p@ss=word'
# Feature flags
FEATURE_X_ENABLED=true
Testing
composer test