PHPackages                             laxity7/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. laxity7/dotenv

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

laxity7/dotenv
==============

Registers environment variables from a .env file

v1.0.4(2mo ago)01.2k↑21.4%MITPHPPHP &gt;=7.4|&gt;=8.0CI failing

Since Feb 2Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/laxity7/dotenv)[ Packagist](https://packagist.org/packages/laxity7/dotenv)[ Docs](https://github.com/laxity7/dotenv)[ RSS](/packages/laxity7-dotenv/feed)WikiDiscussions master Synced yesterday

READMEChangelog (1)Dependencies (10)Versions (6)Used By (0)

PHP DotEnv
==========

[](#php-dotenv)

A fast, lightweight `.env` file parser for PHP. Loads environment variables and makes them accessible via `$_ENV`, `getenv()`, and the built-in `Env::get()` helper.

[![License](https://camo.githubusercontent.com/5333ed9824ae2a80bc9c7311e9c98b8f450cd66a205b1e8f06d3746ea17606ed/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6c6178697479372f646f74656e762e737667)](https://github.com/laxity7/dotenv/blob/master/LICENSE)[![Latest Stable Version](https://camo.githubusercontent.com/676b84e65f9870ac808eccef407b89b5f412b03c4a9803046323b17434b0904c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c6178697479372f646f74656e762e737667)](https://packagist.org/packages/laxity7/dotenv)[![Total Downloads](https://camo.githubusercontent.com/03a64af55730edb0751e271ddb49917531e1869f759b9cebb49b8035f8ac7347/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c6178697479372f646f74656e762e737667)](https://packagist.org/packages/laxity7/dotenv)

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

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Features](#features)
    - [Type Casting](#type-casting)
    - [Variable Interpolation](#variable-interpolation)
    - [Export Prefix](#export-prefix)
    - [Inline Comments](#inline-comments)
    - [Error Tolerance](#error-tolerance)
- [API](#api)
    - [DotEnv](#dotenv)
    - [Env Helper](#env-helper)
- [Comparison with symfony/dotenv](#comparison-with-symfonydotenv)
- [Development](#development)

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

[](#requirements)

- PHP **&gt;=7.4 | 8+**

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

[](#installation)

```
composer require laxity7/dotenv
```

Quick Start
-----------

[](#quick-start)

Create a `.env` file in your project root (make sure it is added to `.gitignore`):

```
APP_NAME=MyApp
APP_DEBUG=true
DB_HOST=localhost
DB_PORT=3306
```

Load it in your application:

```
$dotenv = new \Laxity7\DotEnv\DotEnv();
$dotenv->load(__DIR__ . '/.env');

$dotenv->get('APP_NAME');  // 'MyApp'
$dotenv->get('APP_DEBUG'); // true (boolean)
$dotenv->get('DB_PORT');   // 3306 (integer)
$dotenv->get('MISSING', 'default'); // 'default'
```

All loaded variables are also available in `$_ENV`:

```
$_ENV['APP_NAME']; // 'MyApp'
```

> If the file does not exist, no error is thrown — only already existing environment variables will be available.

You can load additional files. By default, existing variables are **not** overwritten:

```
$dotenv->load(__DIR__ . '/.env');
$dotenv->load(__DIR__ . '/.env.local');       // will not overwrite existing variables
$dotenv->load(__DIR__ . '/.env.local', true); // will overwrite existing variables
```

### Helper Function

[](#helper-function)

For convenience, you can create a global `env()` helper:

```
function env(string $name, $default = null) {
    static $dotenv = null;

    if ($dotenv === null) {
        $dotenv = new \Laxity7\DotEnv\DotEnv();
        $dotenv->load(__DIR__ . '/.env');
    }

    return $dotenv->get($name, $default);
}
```

Or use the built-in `Env` static helper:

```
$dotenv = new \Laxity7\DotEnv\DotEnv();
$dotenv->load(__DIR__ . '/.env');
\Laxity7\DotEnv\Env::load($dotenv);

// Now available anywhere:
\Laxity7\DotEnv\Env::get('APP_NAME');           // 'MyApp'
\Laxity7\DotEnv\Env::get('MISSING', 'default'); // 'default'
\Laxity7\DotEnv\Env::has('APP_NAME');            // true
```

Or combine both approaches for a short `env()` function:

```
$dotenv = new \Laxity7\DotEnv\DotEnv();
$dotenv->load(__DIR__ . '/.env');
\Laxity7\DotEnv\Env::load($dotenv);

function env(string $name, $default = null) {
    return \Laxity7\DotEnv\Env::get($name, $default);
}
```

Features
--------

[](#features)

### Type Casting

[](#type-casting)

Values are automatically cast to native PHP types:

.env valuePHP typePHP value`FOO=hello``string``'hello'``FOO=123``int``123``FOO=3.14``float``3.14``FOO=.5``float``0.5``FOO=true` / `FOO=false``bool``true`/`false``FOO=null``null``null``FOO=``null``null``FOO="true"``string``'true'``FOO="123"``string``'123'`> **Note:** Quoted values (`"..."` or `'...'`) are always treated as strings, even if they look like numbers or booleans.

### Variable Interpolation

[](#variable-interpolation)

Reference previously defined variables using `${VAR}` syntax:

```
APP_NAME=MyApp
APP_ENV=production
APP_TITLE="${APP_NAME} (${APP_ENV})"

DB_HOST=localhost
DB_PORT=3306
DB_NAME=mydb
DATABASE_URL="mysql://${DB_HOST}:${DB_PORT}/${DB_NAME}"
```

```
$dotenv->get('APP_TITLE');    // 'MyApp (production)'
$dotenv->get('DATABASE_URL'); // 'mysql://localhost:3306/mydb'
```

> Interpolation is **not** performed inside single-quoted values: `FOO='${BAR}'` will remain the literal string `${BAR}`.
> If a referenced variable is not defined, it is replaced with an empty string.

### Export Prefix

[](#export-prefix)

Lines prefixed with `export` are supported (common in shell-compatible `.env` files):

```
export APP_ENV=production
export APP_DEBUG=false
```

The `export` keyword is simply stripped — variables are loaded as usual.

### Inline Comments

[](#inline-comments)

Comments are supported both on their own line and inline:

```
# This is a full-line comment
FOO=123 # This is an inline comment
BAR="value #not a comment" # But this is
```

### Error Tolerance

[](#error-tolerance)

Unlike many parsers, this package gracefully handles common formatting issues:

```
FOO =123       # spaces around key
BAR= 456       # space before value
BAZ            # missing = sign (treated as null)
FOOS=foo bar   # unquoted value with spaces
```

All of the above will be parsed without errors.

API
---

[](#api)

### DotEnv

[](#dotenv)

```
$dotenv = new \Laxity7\DotEnv\DotEnv();
```

#### `load(string $path, bool $overrideExistingVars = false, bool $usePutEnv = false): void`

[](#loadstring-path-bool-overrideexistingvars--false-bool-useputenv--false-void)

Load variables from a `.env` file.

- `$path` — path to the `.env` file. If the file does not exist, the call is silently ignored.
- `$overrideExistingVars` — if `true`, variables from the file will overwrite already defined ones.
- `$usePutEnv` — if `true`, also call `putenv()` for each variable (see below).

#### `get(string $name, $default = null): mixed`

[](#getstring-name-default--null-mixed)

Get the value of an environment variable. Returns `$default` if the variable is not defined.

#### `has(string $name): bool`

[](#hasstring-name-bool)

Check whether a variable exists (including variables with a `null` value).

#### `getAll(): array`

[](#getall-array)

Return all loaded environment variables as an associative array.

#### `clear(): void`

[](#clear-void)

Clear the internal variable store. Does **not** modify `$_ENV` or system environment — only resets the internal state.

#### `$usePutEnv` (property)

[](#useputenv-property)

```
$dotenv->usePutEnv = true;
$dotenv->load(__DIR__ . '/.env');
```

When enabled, variables are also registered via `putenv()`, making them accessible through `getenv()`.

> ⚠️ `putenv()` is **not thread-safe**. Use only when you specifically need `getenv()` support.

The `$usePutEnv` parameter in `load()` serves the same purpose but applies only to that single call, while the property applies to all subsequent `load()` calls.

### Env Helper

[](#env-helper)

A static helper class for convenient access from anywhere in your application.

```
\Laxity7\DotEnv\Env::load($dotenv); // initialize with a DotEnv instance
\Laxity7\DotEnv\Env::get('KEY', 'default');
\Laxity7\DotEnv\Env::has('KEY');
```

> Calling `get()` or `has()` before `load()` will throw a `\RuntimeException`.

Comparison with symfony/dotenv
------------------------------

[](#comparison-with-symfonydotenv)

Featurelaxity7/dotenvsymfony/dotenvNative boolean casting✅❌Native int/float casting✅❌Error tolerance✅❌Inline comments✅❌Variable interpolation✅✅`export` prefix✅✅Performance**~4× faster**baseline### Boolean Values

[](#boolean-values)

```
FOO=true
BAR=false
BAZ="false"
```

```
// laxity7/dotenv
$dotenv->get('FOO'); // true  (bool)
$dotenv->get('BAR'); // false (bool)
$dotenv->get('BAZ'); // 'false' (string — it's quoted)

// symfony/dotenv — all values are strings
$_ENV['FOO']; // 'true' (string)
```

### Performance

[](#performance)

Benchmark results (10 000 iterations):

Metriclaxity7/dotenvsymfony/dotenvmin0.0218 ms0.0773 msmax0.3831 ms0.9657 msavg0.0238 ms0.0967 msRun benchmarks yourself:

```
make bench
# or
composer bench
```

### Error Tolerance

[](#error-tolerance-1)

This `.env` file is valid for laxity7/dotenv, but causes exceptions in symfony/dotenv:

```
FOO =123
BAR= 456
BAZ
FOOS=foo bar baz
```

symfony/dotenv errors:

```
Whitespace characters are not supported after the variable name in ".env" at line 1.
Whitespace are not supported before the value in ".env" at line 2.
Missing = in the environment variable declaration in ".env" at line 3.
A value containing spaces must be surrounded by quotes in ".env" at line 4

```

Development
-----------

[](#development)

The project uses Docker for all commands, so no local PHP installation is required.

```
make install   # Install composer dependencies
make test      # Run PHPUnit tests
make phpstan   # Run PHPStan static analysis (level 9 + strict rules)
make bench     # Run benchmark comparison (laxity7 vs symfony)
make check     # Run tests + PHPStan
```

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance85

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity66

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

Total

5

Last Release

79d ago

PHP version history (2 changes)1.0.0PHP &gt;=7.1

v1.0.1PHP &gt;=7.4|&gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/a9b526de35a63bf1110afac0fd4273cd7ae65b360a56504364ff06c1c5ffc533?d=identicon)[laxity7](/maintainers/laxity7)

---

Top Contributors

[![laxity7](https://avatars.githubusercontent.com/u/6792144?v=4)](https://github.com/laxity7 "laxity7 (9 commits)")

---

Tags

environmentenvdotenv

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/laxity7-dotenv/health.svg)](https://phpackages.com/packages/laxity7-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)[diarmuidie/envpopulate

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

1695.7k](/packages/diarmuidie-envpopulate)[zepgram/magento-dotenv

Simple autoloader to integrate the Symfony Dotenv component into Magento2

1376.0k](/packages/zepgram-magento-dotenv)[nystudio107/dotenvy

Speed up your production sites by ditching .env for key/value variable pairs as Apache, Nginx, and shell equivalents.

317.0k](/packages/nystudio107-dotenvy)[dotenv-org/phpdotenv-vault

Load environment variables from encrypted .env.vault files

1019.5k2](/packages/dotenv-org-phpdotenv-vault)

PHPackages © 2026

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