PHPackages                             code-distortion/fluent-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. code-distortion/fluent-dotenv

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

code-distortion/fluent-dotenv
=============================

A wrapper with a fluent interface for new and old versions of vlucas/phpdotenv or symfony/dotenv, providing a common interface to easily read values from .env files

0.3.5(5mo ago)3102.2k↓36.2%2[1 PRs](https://github.com/code-distortion/fluent-dotenv/pulls)3MITPHPPHP 7.0.\* | 7.1.\* | 7.2.\* | 7.3.\* | 7.4.\* | 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\* | 8.4.\* | 8.5.\*CI passing

Since Jul 15Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/code-distortion/fluent-dotenv)[ Packagist](https://packagist.org/packages/code-distortion/fluent-dotenv)[ Docs](https://github.com/code-distortion/fluent-dotenv)[ RSS](/packages/code-distortion-fluent-dotenv/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (6)Versions (15)Used By (3)

FluentDotEnv
============

[](#fluentdotenv)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c19dcb138061fe87229bcb17e73df444585fb5182cc01f3211c3c8c492862a26/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64652d646973746f7274696f6e2f666c75656e742d646f74656e762e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/code-distortion/fluent-dotenv)[![PHP Version](https://camo.githubusercontent.com/7377a12d33082dcc66e398bcdfe01550146ac043eef13190ae9c5c99018ee3a0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d372e30253230746f253230382e352d626c75653f7374796c653d666c61742d737175617265)](https://php.net)[![vlucas/phpdotenv](https://camo.githubusercontent.com/6a3d15d80eb08ba8b23cca4a8961a7b84aa3ffb0b087fe3e279843ef8a03943b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f766c75636173253246706870646f74656e762d312e31253230746f253230352e782d626c75653f7374796c653d666c61742d737175617265)](https://github.com/vlucas/phpdotenv)[![symfony/dotenv](https://camo.githubusercontent.com/7b572b8fc1a24ede2ffea385d2312cff62f125aac52bfc6ab280bb47d051cee4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f73796d666f6e79253246646f74656e762d332e33253230746f253230372e782d626c75653f7374796c653d666c61742d737175617265)](https://github.com/symfony/dotenv)[![GitHub Workflow Status](https://camo.githubusercontent.com/48f0b6109ceb06f094890315b7da7229766d7276f82ae620ab513e29822d959b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636f64652d646973746f7274696f6e2f666c75656e742d646f74656e762f72756e2d74657374732e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/code-distortion/fluent-dotenv/actions)[![Buy The World a Tree](https://camo.githubusercontent.com/dc3f77a9b22c3bc83c7b7d863bf138a7ca3418f1826b0b16d073d0aa87c16bc4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74726565776172652d2546302539462538432542332d6c69676874677265656e3f7374796c653d666c61742d737175617265)](https://plant.treeware.earth/code-distortion/fluent-dotenv)[![Contributor Covenant](https://camo.githubusercontent.com/902d296a65b2997bada7e7717fd929d9177f3bd95414cbb5ea2ed843c680f314/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f6e7472696275746f72253230636f76656e616e742d76322e3125323061646f707465642d6666363962342e7376673f7374796c653d666c61742d737175617265)](.github/CODE_OF_CONDUCT.md)

***code-distortion/fluent-dotenv*** is a wrapper with a fluent interface for new and old versions of [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) and [symfony/dotenv](https://github.com/symfony/dotenv), providing a common interface to easily read values from .env files.

Table of Contents
-----------------

[](#table-of-contents)

- [Introduction](#introduction)
- [Overview](#overview)
- [Installation](#installation)
- [Usage](#usage)
    - [Reading values from .env files](#reading-values-from-env-files)
    - [Filtering](#filtering)
    - [Validation](#validation)
    - [Casting values](#casting-values)
    - [Calling order](#calling-order)
    - [Populating $\_ENV and $\_SERVER superglobals](#populating-_env-and-_server-superglobals)
    - [Putenv() and getenv()](#putenv-and-getenv)
    - [Picking vlucas/phpdotenv or symfony/dotenv](#picking-vlucasphpdotenv-or-symfonydotenv)
- [Testing This Package](#testing-this-package)
- [Changelog](#changelog)
    - [SemVer](#semver)
- [Treeware](#treeware)
- [Contributing](#contributing)
    - [Code of Conduct](#code-of-conduct)
    - [Security](#security)
- [Credits](#credits)
- [License](#license)

Introduction
------------

[](#introduction)

.env files are an important tool as they allow for customisation of projects between environments.

The motivation behind this package is to provide a way to interact with the different versions of [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) or [symfony/dotenv](https://github.com/symfony/dotenv) with a single interface.

This has been helpful for me when building packages that need to support a wide range of other packages.

> First released in 2013, [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) by Vance Lucas and Graham Campbell is the most used PHP solution for loading values from .env files. Please have a look at their page for a more detailed description of what .env files are and why they're used.

> [symfony/dotenv](https://github.com/symfony/dotenv) was first released in 2017 as an alternative that's a part of [Symfony framework](https://github.com/symfony) family.

Overview
--------

[](#overview)

This package provides a new fluent interface for [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) and [symfony/dotenv](https://github.com/symfony/dotenv), and adds new features, including the ability to:

- Perform validation - make sure values are *not empty*, are *integers*, *booleans*, are *limited to a specific set of values*, match a *regex* or validate via a *callback*,
- Specify values to explicitly *pick* or *ignore*,
- Specify values that are *required*,
- Type casting to *boolean* or *integer*,
- Populate *$\_ENV* and *$\_SERVER* values if you like, choosing whether to override values that already exist or not.

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

[](#installation)

Install the package via composer:

```
composer require code-distortion/fluent-dotenv
```

You must also include either `vlucas/phpdotenv` or `symfony/dotenv` in your project:

```
composer require vlucas/phpdotenv
# or
composer require symfony/dotenv
```

FluentDotEnv will automatically detect which of these dotenv packages are installed and use it. You can also [choose](#picking-vlucasphpdotenv-or-symfonydotenv) explicitly if you like.

Usage
-----

[](#usage)

### Reading values from .env files

[](#reading-values-from-env-files)

```
use CodeDistortion\FluentDotEnv\FluentDotEnv;

// simply load the values from one or more .env files
$fDotEnv = FluentDotEnv::new()->load('path/to/.env');
$fDotEnv = FluentDotEnv::new()->load(['path/to/.env', 'path/to/another.env']);

// don't throw an exception if the file doesn't exist
$fDotEnv = FluentDotEnv::new()->safeLoad('path/to/missing.env');

// get all the loaded values as an associative array
$allValues = $fDotEnv->all();

// get a single value
$host = $fDotEnv->get('HOST');

// get several values (returned as an associative array)
$dbCredentials = $fDotEnv->get(['HOST', 'PORT', 'USERNAME', 'PASSWORD']);
```

> ***NOTE:*** Over time, vlucas/phpdotenv and symfony/dotenv have improved the way they interpret values from .env files (e.g. multi-line variables). The underlying version of these package/s you use will determine how the .env values are interpreted.

### Filtering

[](#filtering)

If you only want to load specific keys, you can specify them. Other values from your .env file will be ignored:

```
$fDotEnv = FluentDotEnv::new()
    ->pick('MY_KEY1')              // add a key to pick
    ->pick('MY_KEY2')              // values can be passed individually
    ->pick(['MY_KEY3', 'MY_KEY4']) // or multiple as an array
    ->load('path/to/.env');
```

Conversely, particular keys can be ignored:

```
$fDotEnv = FluentDotEnv::new()
    ->ignore('MY_KEY1')              // add a key to ignore
    ->ignore('MY_KEY2')              // values can be passed individually
    ->ignore(['MY_KEY3', 'MY_KEY4']) // or multiple as an array
    ->load('path/to/.env');
```

### Validation

[](#validation)

Validation can be applied to the values in an .env file. A `CodeDistortion\FluentDotEnv\Exceptions\ValidationException` exception will be thrown when a value fails validation:

```
$fDotEnv = FluentDotEnv::new()

    // make sure these keys exist
    ->required('MY_KEY')
    ->required(['MY_KEY1', 'MY_KEY2'])

    // when these keys exist, make sure they aren't empty
    ->notEmpty('MY_KEY')
    ->notEmpty(['MY_KEY1', 'MY_KEY2'])

    // when these keys exist, make sure they are integer strings
    ->integer('MY_KEY')
    ->integer(['MY_KEY1', 'MY_KEY2'])

    // when these keys exist, make sure they are boolean strings
    // i.e. "true", "false", "On", "Off", "Yes", "No", "1" and "0"
    ->boolean('MY_KEY')
    ->boolean(['MY_KEY1', 'MY_KEY2'])

    // when a key exists, make sure its value is in a predefined list
    ->allowedValues('MY_KEY', ['value-1', 'value-2'])
    // allow predefined values for a multiple keys
    ->allowedValues(['MY_KEY1', 'MY_KEY2'], ['value-1', 'value-2'])
    // different predefined values can be specified for different keys in one go
    ->allowedValues([
        'MY_KEY1' => ['value-1', 'value-2'],
        'MY_KEY2' => ['value-a', 'value-b'],
    ])

    // when a key exists, make sure its value matches a regular expression
    ->regex('MY_KEY', '/^[0-9]+\.[0-9]{2}$/')
    // the same regex can be applied to multiple keys
    ->regex(['MY_KEY1', 'MY_KEY2'], '/^[0-9]+\.[0-9]{2}$/')
    // different regexes can be applied to different keys in one go
    ->regex([
        'MY_KEY1' => '/^[0-9]+\.[0-9]{2}$/',
        'MY_KEY2' => '/^[a-z]+$/'
    ])

    // when a key exists, validate it's value via a callback
    ->callback('MY_KEY', $callback)
    // the same callback can be applied to multiple keys
    ->callback(['MY_KEY1', 'MY_KEY2'], $callback)
    // different callbacks can be applied to different keys in one go
    ->callback([
        'MY_KEY1' => $callback1,
        'MY_KEY2' => $callback2,
    ])
    // validate *all* values via a callback
    ->callback(function (string $key, $value) {
        return true; // or false
    })

    // the validation is applied when load is called
    ->load('path/to/.env');
```

### Casting values

[](#casting-values)

Values retrieved using `get(…)` or `all(…)` are returned as strings.

`castBoolean(…)` and `castInteger(…)` are available for convenience to retrieve values as booleans or integers (`null` will be returned when the values aren't "booleans" or integers).

```
$fDotEnv = FluentDotEnv::new()->load('path/to/.env');

// cast to a boolean when the value is one of:
// "true", "false", "On", "Off", "Yes", "No", "1" and "0"
$boolean = $fDotEnv->castBoolean('MY_KEY');
$booleans = $fDotEnv->castBoolean(['MY_KEY1', 'MY_KEY2']);

// cast to an integer, including negative numbers
$integer = $fDotEnv->castInteger('MY_KEY');
$integers = $fDotEnv->castInteger(['MY_KEY1', 'MY_KEY2']);
```

### Calling order

[](#calling-order)

It doesn't matter which order you call the methods above in, they can be called *before* or *after* loading values from .env files. e.g.

```
$fDotEnv = FluentDotEnv::new()
    ->load('path/to/.env') // loaded at the beginning
    ->pick(['MY_KEY1', 'MY_KEY2'])
    ->integer('MY_KEY1')
    ->boolean('MY_KEY2')
    ->populateEnv();

$fDotEnv = FluentDotEnv::new()
    ->pick(['MY_KEY1', 'MY_KEY2']) // deferred
    ->integer('MY_KEY1') // deferred
    ->boolean('MY_KEY2') // deferred
    ->populateEnv() // deferred
    ->load('path/to/.env'); // loaded at the end
```

> ***NOTE:*** When you call `populateEnv()` or `populateServer()` *after* `load()` has been called, the $\_ENV and $\_SERVER arrays respectively will be updated straight away.

### Populating $\_ENV and $\_SERVER superglobals

[](#populating-_env-and-_server-superglobals)

By default, the $\_ENV and $\_SERVER superglobals are not changed when loading .env values.

However, you can choose to populate them by calling `populateEnv(…)` and `populateServer(…)` respectively. e.g.

```
$fDotEnv = FluentDotEnv::new()

    // add the loaded values to $_ENV
    ->populateEnv()
    // add values to $_ENV and override values that already exist
    ->populateEnv(true)

    // add the loaded values to $_SERVER
    ->populateServer()
    // add values to $_SERVER and override values that already exist
    ->populateServer(true)

    // the values are added when load is called
    ->load('path/to/.env');
```

### Putenv() and getenv()

[](#putenv-and-getenv)

The `putenv(…)` and `getenv(…)` functions are not thread-safe, which may cause issues in a multi-threaded environment. For this reason this functionality is not included in this package. You can read discussion about this [here](https://github.com/vlucas/phpdotenv/issues/76) and [here](https://github.com/symfony/symfony/discussions/49928).

> ***NOTE:*** If you're using symfony/dotenv, you may want to consider using version 5.1.0 or higher…
>
> symfony/dotenv [added an option to turn off the use of putenv()](https://github.com/symfony/dotenv/commit/e1f27138406a700c01d4e05e861226bb0c28b83a#diff-b73348fec7eb6dfdb482d959a985979c5bead6091837e488319d75983556f5e7R74-L74) in version 5.1.0. FluentDotEnv uses this to make sure the environment variables don't get changed. However, in earlier versions putenv() is used without a way to turn it off.
>
> FluentDotEnv hides this away, leaving your environment variables the same as they were before loading. ***But***, it means that environment variables are changed temporarily during the `->load()` process.

### Picking vlucas/phpdotenv or symfony/dotenv

[](#picking-vlucasphpdotenv-or-symfonydotenv)

You need to include either vlucas/phpdotenv or symfony/dotenv in your project:

```
composer require vlucas/phpdotenv
# or
composer require symfony/dotenv
```

FluentDotEnv will try to use vlucas/phpdotenv first, then symfony/dotenv.

If you have both installed and want to be particular about which one is used, you can call `useVlucasPhpDotEnv()` or `useSymfonyDotEnv()` before calling `load()`. e.g.

```
$fDotEnv = FluentDotEnv::new()
    ->useVlucasPhpDotEnv()
    ->load('path/to/.env');
```

```
$fDotEnv = FluentDotEnv::new()
    ->useSymfonyDotEnv()
    ->load('path/to/.env');
```

If neither are found, a `CodeDistortion\FluentDotEnv\Exceptions\DependencyException` will be thrown.

Testing This Package
--------------------

[](#testing-this-package)

- Clone this package: `git clone https://github.com/code-distortion/fluent-dotenv.git .`
- Run `composer install` to install dependencies
- Run the tests: `composer test`

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

### SemVer

[](#semver)

This library uses [SemVer 2.0.0](https://semver.org/) versioning. This means that changes to `X` indicate a breaking change: `0.0.X`, `0.X.y`, `X.y.z`. When this library changes to version 1.0.0, 2.0.0 and so forth, it doesn't indicate that it's necessarily a notable release, it simply indicates that the changes were breaking.

Treeware
--------

[](#treeware)

This package is [Treeware](https://treeware.earth). If you use it in production, then we ask that you [**buy the world a tree**](https://plant.treeware.earth/code-distortion/fluent-dotenv) to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

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

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

### Code of Conduct

[](#code-of-conduct)

Please see [CODE\_OF\_CONDUCT](.github/CODE_OF_CONDUCT.md) for details.

### Security

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Tim Chandler](https://github.com/code-distortion)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

51

—

FairBetter than 96% of packages

Maintenance70

Regular maintenance activity

Popularity35

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity70

Established project with proven stability

 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 ~150 days

Recently: every ~176 days

Total

14

Last Release

176d ago

PHP version history (7 changes)0.1.0PHP ^7.0

0.1.1PHP ^7.0 | ^8.0

0.1.3PHP 7.0.\* | 7.1.\* | 7.2.\* | 7.3.\* | 7.4.\* | 8.0.\* | 8.1.\*

0.1.6PHP 7.0.\* | 7.1.\* | 7.2.\* | 7.3.\* | 7.4.\* | 8.0.\* | 8.1.\* | 8.2.\*

0.2.0PHP 7.0.\* | 7.1.\* | 7.2.\* | 7.3.\* | 7.4.\* | 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\*

0.3.4PHP 7.0.\* | 7.1.\* | 7.2.\* | 7.3.\* | 7.4.\* | 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\* | 8.4.\*

0.3.5PHP 7.0.\* | 7.1.\* | 7.2.\* | 7.3.\* | 7.4.\* | 8.0.\* | 8.1.\* | 8.2.\* | 8.3.\* | 8.4.\* | 8.5.\*

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/56794290?v=4)[Tim](/maintainers/code-distortion)[@code-distortion](https://github.com/code-distortion)

---

Top Contributors

[![code-distortion](https://avatars.githubusercontent.com/u/56794290?v=4)](https://github.com/code-distortion "code-distortion (41 commits)")

---

Tags

polyfillconfigenvironmentwrapperenvdotenvphpdotenvvlucassymfony dotenvvlucas phpdotenv

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/code-distortion-fluent-dotenv/health.svg)

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

###  Alternatives

[vlucas/phpdotenv

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

13.5k602.4M5.4k](/packages/vlucas-phpdotenv)[symfony/dotenv

Registers environment variables from a .env file

3.8k226.7M2.3k](/packages/symfony-dotenv)[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.0M21](/packages/m1-env)[cekurte/environment

A library to get the values from environment variables and process to php data types

5884.0k7](/packages/cekurte-environment)[diarmuidie/envpopulate

Tool to interactively populate a `.env` file based on an `.env.example` file whenever Composer installs or updates.

1892.0k](/packages/diarmuidie-envpopulate)[beebmx/kirby-env

Enable env variables to Kirby

2037.9k2](/packages/beebmx-kirby-env)

PHPackages © 2026

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