PHPackages                             initphp/dotenv - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. initphp/dotenv

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

initphp/dotenv
==============

Loads environment variables from a .env or .env.php file, with type coercion and ${VAR} interpolation.

3.1.0(1w ago)113011MITPHPPHP &gt;=8.0CI passing

Since Mar 15Pushed 1w ago1 watchersCompare

[ Source](https://github.com/InitPHP/DotENV)[ Packagist](https://packagist.org/packages/initphp/dotenv)[ GitHub Sponsors](https://github.com/muhammetsafak)[ RSS](/packages/initphp-dotenv/feed)WikiDiscussions main Synced today

READMEChangelog (4)Dependencies (3)Versions (7)Used By (1)

InitPHP DotENV
==============

[](#initphp-dotenv)

Loads environment variables from a `.env` or `.env.php` file into PHP's environment (`$_ENV`, `$_SERVER`, `getenv()`), with type coercion and `${VAR}` interpolation.

[![CI](https://github.com/InitPHP/DotENV/actions/workflows/ci.yml/badge.svg)](https://github.com/InitPHP/DotENV/actions/workflows/ci.yml)[![Latest Stable Version](https://camo.githubusercontent.com/f53a2fd01f284cb9c48776c891271e41ea5101d7bc335d23ac8873700d29c482/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f646f74656e762f76)](https://packagist.org/packages/initphp/dotenv) [![Total Downloads](https://camo.githubusercontent.com/cbe494d0693c07e2751a99fc87088f919b65577662fd5541382dc851c687479e/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f646f74656e762f646f776e6c6f616473)](https://packagist.org/packages/initphp/dotenv) [![License](https://camo.githubusercontent.com/1e5631eb1e75c3f6dfcf2fb99f9b924db0d8d0409ad7ecb089a53246eb29d9c9/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f646f74656e762f6c6963656e7365)](https://packagist.org/packages/initphp/dotenv) [![PHP Version Require](https://camo.githubusercontent.com/f4696c381f63fe55c26c4943939997f68aef7def16c4ded91ab447f834a680db/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f646f74656e762f726571756972652f706870)](https://packagist.org/packages/initphp/dotenv)

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- No extensions beyond the PHP core

Installation
------------

[](#installation)

```
composer require initphp/dotenv
```

Quick start
-----------

[](#quick-start)

`/home/www/.env`:

```
# Comment line
SITE_URL = http://lvh.me
PAGE_URL = ${SITE_URL}/page

; Another comment
TRUE_VALUE  = true
FALSE_VALUE = false
NULL_VALUE  = null
EMPTY_VALUE = empty

NUMERIC_VALUE = 13
PI_NUMBER     = 3.14
ZIP_CODE      = 007
```

```
require 'vendor/autoload.php';

use InitPHP\DotENV\DotENV;

DotENV::create('/home/www/.env');     // or DotENV::create('/home/www');

DotENV::get('SITE_URL');      // "http://lvh.me"
DotENV::get('PAGE_URL');      // "http://lvh.me/page"
DotENV::get('TRUE_VALUE');    // true       (bool)
DotENV::get('FALSE_VALUE');   // false      (bool)
DotENV::get('NULL_VALUE');    // null
DotENV::get('EMPTY_VALUE');   // ""         (string)
DotENV::get('NUMERIC_VALUE'); // 13         (int)
DotENV::get('PI_NUMBER');     // 3.14       (float)
DotENV::get('ZIP_CODE');      // "007"      (string — leading zero preserved)

DotENV::get('NOT_FOUND', 'hi'); // "hi"

env('SITE_URL');              // global helper, same shared state
```

Prefer an isolated instance (e.g. for DI or tests)? Use the `Repository`directly:

```
use InitPHP\DotENV\Repository;

$env = new Repository();
$env->create('/home/www/.env');
$env->get('SITE_URL');
```

File format in brief
--------------------

[](#file-format-in-brief)

- `KEY = VALUE` — split on the first `=`; whitespace around the key is trimmed.
- Comments start a line with anything other than a letter/digit/`_`/`-`(`#`, `;`, `//`); inline comments start at a `#` preceded by whitespace.
- Quote a value (`"..."` or `'...'`) to keep it verbatim, including a leading `#` such as `#ffffff`.
- `${OTHER}` references are expanded when the value is read.
- `true` / `false` / `null` / `empty` and round-tripping numbers are coerced; everything else stays a string.

Full details: [`docs/`](docs/README.md).

API summary
-----------

[](#api-summary)

CallReturnsPurpose`DotENV::create(string $path, bool $debug = true)``void`Load a `.env`/`.env.php` file or a directory containing one.`DotENV::get(string $name, mixed $default = null)``mixed`Read a value (`$_ENV` → `$_SERVER` → `getenv()`).`DotENV::env(string $name, mixed $default = null)``mixed`Alias of `get()`.`DotENV::flush()``void`Unload everything this instance defined.`DotENV::reset()``void``flush()` and drop the shared instance.`DotENV::drift(string|array $reference, array $options = [])``DriftReport`Compare the loaded env against a reference and report drift.`DotENV::assertNoDrift(string|array $reference, array $options = [])``void`Strict mode: throw `DriftException` when drift is found.`env(string $name, mixed $default = null)``mixed`Global helper for `DotENV::get()`.`env_drift(string|array $reference, array $options = [])``DriftReport`Global helper for `DotENV::drift()`.See the [API reference](docs/api-reference.md) for details.

Env drift
---------

[](#env-drift)

Once an env file is loaded you can check it for **drift** against a reference — the keys that *should* be present. It catches the failure that bites in CI/production: a key your code expects that was never provisioned.

The reference can be a **`.env.example` path** (the usual convention) or a **required-keys array**:

```
use InitPHP\DotENV\DotENV;

DotENV::create('/home/www/.env');

// Reference = a checked-in example file.
$report = DotENV::drift('/home/www/.env.example');

// Reference = an explicit required-keys list.
$report = DotENV::drift(['DB_HOST', 'DB_PORT', 'APP_KEY']);

if ($report->hasDrift()) {
    echo $report;                 // human-readable summary for the log
    $report->getMissing();        // ['APP_KEY']
    $report->toArray();           // ['missing' => [...], 'extra' => [...], 'empty' => [...]]
}
```

Drift is grouped into three buckets:

BucketMeaningDefault**missing**a reference key absent from the actual environmentalways reported**extra**a key this loader defined that is **not** in the referenceopt-in (`['extra' => true]`)**empty**a reference key that is present but blankopt-in (`['empty' => true]`)`extra` and `empty` are off by default: extra keys are usually noise, and only keys *this loader defined* are ever considered for `extra` (unrelated OS variables are never reported).

```
// Also flag undocumented and blank-but-required keys.
$report = DotENV::drift('/home/www/.env.example', ['extra' => true, 'empty' => true]);
```

### Strict mode (CI gate)

[](#strict-mode-ci-gate)

`assertNoDrift()` runs the same comparison and throws a [`DriftException`](docs/exceptions.md) the moment any drift is found — drop it into a bootstrap or a CI check to fail fast:

```
use InitPHP\DotENV\Exceptions\DriftException;

try {
    DotENV::assertNoDrift('/home/www/.env.example');
} catch (DriftException $e) {
    fwrite(STDERR, $e->getMessage() . PHP_EOL);
    fwrite(STDERR, implode(', ', $e->getReport()->getMissing()) . PHP_EOL);
    exit(1);
}
```

`DriftException` extends `DotENVException` (and `InvalidArgumentException`), so existing catch blocks keep working, and the offending `DriftReport` is attached via `getReport()`.

Drift checking is **read-only**: it never defines, reads-through, or mutates any environment value, so it is safe to run after `create()` without changing what is loaded. See [`docs/env-drift.md`](docs/env-drift.md) for the full reference.

Notes
-----

[](#notes)

- **Immutability:** values already in `$_ENV` or `$_SERVER` are never overwritten, so real environment variables win over a committed `.env`.
- **`$debug`:** when `false`, `create()` swallows every error (missing file, wrong type, unreadable) instead of throwing a [`DotENVException`](docs/exceptions.md).
- **Security:** keep `.env` files out of the web root, and remember a `.env.php` file is executed as code — see the [security notes](docs/security.md).

Upgrading from 2.x
------------------

[](#upgrading-from-2x)

3.0 is a maintenance-focused major release. The public API (`DotENV::create`, `get`, `env` and the `env()` helper) is unchanged, but note:

- **PHP 8.0+** is now required (was 5.6+).
- **Numbers are only coerced when it is loss-free.** `007` and `+90555…` now stay strings instead of becoming `7` and a float.
- Real bug fixes change previously broken results: directory-path loading, multiple `${VAR}` references on one line, quoted values with spaces around `=`, and values like `#ffffff` all work now.
- The internal `Lib` class is renamed `Repository`; `Lib` remains as a deprecated alias.

See the [changelog](CHANGELOG.md) for the full list.

Contributing
------------

[](#contributing)

Bug reports and pull requests are welcome. The CI runs PHP-CS-Fixer, PHPStan (max level) and PHPUnit across PHP 8.0–8.4; run the same bundle locally with:

```
composer ci
```

Credits
-------

[](#credits)

- [Muhammet ŞAFAK](https://www.muhammetsafak.com.tr) &lt;&gt;

License
-------

[](#license)

Copyright © 2022 InitPHP — released under the [MIT License](./LICENSE).

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance98

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~312 days

Recently: every ~303 days

Total

6

Last Release

13d ago

Major Versions

1.0 → 2.02023-02-24

2.x-dev → 3.0.02026-06-08

PHP version history (3 changes)1.0PHP &gt;=7.4

2.0PHP &gt;=5.6

3.0.0PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/4b6b34f3ac8938d8ee52ba3bd260680855dc5715c7b2929d9380de30d15a67dd?d=identicon)[muhammetsafak](/maintainers/muhammetsafak)

---

Top Contributors

[![muhammetsafak](https://avatars.githubusercontent.com/u/104234499?v=4)](https://github.com/muhammetsafak "muhammetsafak (7 commits)")

---

Tags

12factorconfigconfigurationdotenvenvenv-fileenvironment-variablesgetenvinitphpphpphp8configurationconfigenvironmentenvdotenv12factorgetenvinitphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/initphp-dotenv/health.svg)

```
[![Health](https://phpackages.com/badges/initphp-dotenv/health.svg)](https://phpackages.com/packages/initphp-dotenv)
```

###  Alternatives

[vlucas/phpdotenv

Loads environment variables from `.env` to `getenv()`, `$\_ENV` and `$\_SERVER` automagically.

13.5k640.2M6.3k](/packages/vlucas-phpdotenv)[symfony/dotenv

Registers environment variables from a .env file

3.8k243.3M2.8k](/packages/symfony-dotenv)[helhum/dotenv-connector

Makes it possible to set environment variables for composer projects.

1634.9M41](/packages/helhum-dotenv-connector)[m1/env

Env is a lightweight library bringing .env file parser compatibility to PHP. In short - it enables you to read .env files with PHP.

6412.8M24](/packages/m1-env)[sroze/companienv

Companion for .env files

246424.9k1](/packages/sroze-companienv)[zepgram/magento-dotenv

Simple autoloader to integrate the Symfony Dotenv component into Magento2

1376.0k](/packages/zepgram-magento-dotenv)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
