PHPackages                             sodaho/env-loader - 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. sodaho/env-loader

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

sodaho/env-loader
=================

Lightweight .env file loader for PHP

v1.0.0(3mo ago)07MITPHPPHP ^8.2CI passing

Since Mar 19Pushed 3w agoCompare

[ Source](https://github.com/SoDaHo/env-loader)[ Packagist](https://packagist.org/packages/sodaho/env-loader)[ RSS](/packages/sodaho-env-loader/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (3)Versions (2)Used By (0)

env-loader
==========

[](#env-loader)

Lightweight .env file loader for PHP. Zero dependencies.

Why This Library?
-----------------

[](#why-this-library)

There are established .env loaders for PHP, most notably [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv). This library exists because we needed something simpler:

- **Zero dependencies** — Nothing to install besides this package.
- **Thread-safe by design** — Only writes to `$_ENV`. No `putenv()`/`getenv()`, which are not thread-safe in async runtimes (Swoole, RoadRunner, FrankenPHP).
- **No magic** — No variable expansion (`${VAR}`), no multiline values, no interpreted escape sequences (`\n`, `\t`). What you write is what you get.
- **Minimal footprint** — Easy to audit, easy to understand.

If you need variable expansion, multiline values, or `getenv()` support, use phpdotenv instead.

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

[](#installation)

```
composer require sodaho/env-loader
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use Sodaho\EnvLoader\EnvLoader;

// Loads .env into $_ENV (does not overwrite existing, no required keys)
EnvLoader::load(__DIR__ . '/.env');

echo $_ENV['DB_HOST'];
```

### Options

[](#options)

```
// Overwrite existing $_ENV variables
EnvLoader::load('.env', overwrite: true);

// Require specific keys (throws exception if missing)
EnvLoader::load('.env', required: ['DB_HOST', 'DB_NAME']);

// Required keys as comma-separated string
EnvLoader::load('.env', required: 'DB_HOST,DB_NAME');

// Combine options
EnvLoader::load('.env', overwrite: true, required: ['DB_HOST']);
```

### Parse Without Loading

[](#parse-without-loading)

```
// Returns array without setting $_ENV
$values = EnvLoader::parse('.env');

print_r($values);
// ['DB_HOST' => 'localhost', 'DB_NAME' => 'myapp', ...]
```

Supported .env Syntax
---------------------

[](#supported-env-syntax)

```
# Comments
DB_HOST=localhost

# Empty values
EMPTY_VAR=

# Values with equals sign
PASSWORD=val=ue=with=equals

# Double quotes (supports escaped quotes)
MESSAGE="Hello World"
ESCAPED="Say \"Hello\""

# Single quotes (no escape processing)
SINGLE='Hello World'

# Inline comments
API_KEY=secret123 # this is ignored
QUOTED="value with # hash" # comment outside quotes

# export prefix
export DB_PORT=3306

# Whitespace is trimmed
  SPACED_KEY  =  value
```

Exceptions
----------

[](#exceptions)

All exceptions extend `EnvLoaderException` for easy catching:

```
use Sodaho\EnvLoader\EnvLoader;
use Sodaho\EnvLoader\Exception\EnvLoaderException;
use Sodaho\EnvLoader\Exception\FileNotFoundException;
use Sodaho\EnvLoader\Exception\MissingRequiredKeyException;

try {
    EnvLoader::load('.env', required: ['API_KEY']);
} catch (FileNotFoundException $e) {
    // File does not exist
} catch (MissingRequiredKeyException $e) {
    // Required key not found
} catch (EnvLoaderException $e) {
    // Any other EnvLoader error
}
```

ExceptionWhen`FileNotFoundException`File does not exist or is a directory`FileNotReadableException`File exists but not readable`InvalidKeyException`Key has invalid format (e.g. `123KEY`, `MY-KEY`)`UnterminatedQuoteException`Quoted value missing closing quote`MissingRequiredKeyException`Required key missing after loadingKey Naming Rules
----------------

[](#key-naming-rules)

Valid keys must:

- Start with a letter or underscore
- Contain only letters, numbers, and underscores

```
DB_HOST      ✓
_PRIVATE     ✓
API_KEY_2    ✓
123KEY       ✗ (starts with number)
MY-KEY       ✗ (contains hyphen)
MY KEY       ✗ (contains space)

```

Why $\_ENV Only?
----------------

[](#why-_env-only)

This library intentionally writes **only to `$_ENV`**, not `putenv()` or `$_SERVER`.

**Reason: Thread Safety**

`putenv()` and `getenv()` are **not thread-safe**. In modern PHP runtimes like:

- Swoole
- RoadRunner
- FrankenPHP
- ReactPHP

...concurrent requests can overwrite each other's environment variables, causing hard-to-debug race conditions.

`$_ENV` is process-local and safe. Use `$_ENV['KEY']` instead of `getenv('KEY')` in your application.

```
// Safe
$host = $_ENV['DB_HOST'];

// Not recommended (not set by this loader)
$host = getenv('DB_HOST');
```

When to Use
-----------

[](#when-to-use)

- Development environments
- Shared hosting where system ENV is not available
- Simple projects without framework
- **Modern async PHP** (Swoole, RoadRunner, FrankenPHP)

When NOT to Use
---------------

[](#when-not-to-use)

- Production with proper system ENV configuration
- When you need variable expansion (`${OTHER_VAR}`)
- When you need multiline values
- When you must support legacy code using `getenv()`

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

[](#requirements)

- PHP ^8.2

Acknowledgments
---------------

[](#acknowledgments)

Parts of this project (refactoring, documentation, code review) were developed with AI assistance (Claude).

License
-------

[](#license)

MIT

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance89

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

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

Unknown

Total

1

Last Release

96d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4407ed68227862f26dfbd1fff5c4d117c89ba024bf20202280d00d8199036cfc?d=identicon)[SoDaHo](/maintainers/SoDaHo)

---

Top Contributors

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

---

Tags

dotenvenvenvironmentphpconfigloaderenvironmentenvdotenv

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sodaho-env-loader/health.svg)

```
[![Health](https://phpackages.com/badges/sodaho-env-loader/health.svg)](https://phpackages.com/packages/sodaho-env-loader)
```

###  Alternatives

[vlucas/phpdotenv

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

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

Registers environment variables from a .env file

3.8k237.6M2.6k](/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.

6112.5M23](/packages/m1-env)[cekurte/environment

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

5886.2k8](/packages/cekurte-environment)[diarmuidie/envpopulate

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

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

Simple autoloader to integrate the Symfony Dotenv component into Magento2

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

PHPackages © 2026

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