PHPackages                             socarrat/environment - 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. socarrat/environment

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

socarrat/environment
====================

A super simple dotenv file parser that is compatible with getenv().

v0.1.0(3y ago)16[1 PRs](https://github.com/socarrat-php/environment/pulls)MITPHP

Since May 6Pushed 2y ago1 watchersCompare

[ Source](https://github.com/socarrat-php/environment)[ Packagist](https://packagist.org/packages/socarrat/environment)[ RSS](/packages/socarrat-environment/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (3)Used By (0)

Socarrat\\Environment
=====================

[](#socarratenvironment)

A super simple `.env` file parser that is compatible with [`getenv()`](https://www.php.net/manual/en/function.getenv.php).

[![Test](https://github.com/socarrat-php/environment/actions/workflows/test.yml/badge.svg?event=push)](https://github.com/socarrat-php/environment/actions/workflows/test.yml)

Features
--------

[](#features)

- Parses `.env` files and does it well
- Parses `.env` files from the filesystem and from string input
- [Special characters](#special-characters)
- [Compatible with `getenv()`](#how-about-getenv): no need to adapt your existing applications
- Fault-tolerant
- [Well-tested](#testing)
- [Multi-line values](#multi-line-values)
- Support for comments (WIP)
- Invalid file warnings (WIP)

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

[](#installation)

Download this [package](https://packagist.org/packages/socarrat/environment) on Packagist:

```
composer require socarrat/environment
```

Usage
-----

[](#usage)

The [`EnvironmentManager`](#class-socarratenvironmentenvironmentmanager) is responsible for parsing `.env` files [on the filesystem](#static-public-function-parsefsstring-rootdir-bool-putenv--true) (or, if you like, [as strings](#static-public-function-parsestringstring-envfile-bool-putenv--true)). It does so on request: you need to call one (or more) of the parsing methods (see [API](#api)) to load your environment variables.

### How about `getenv()`?

[](#how-about-getenv)

One of the parameters of the parse functions is `bool $putenv`. If you set this to true (default), [`putenv()`](https://www.php.net/manual/en/function.putenv.php) will be called for every parsed variable. If you already use `getenv()`, there's no need to adapt your program: you only need to call a parse function once at the start.

### Examples

[](#examples)

See the [`examples/` directory](./examples/) for some usage examples.

`.env` file format
------------------

[](#env-file-format)

### The basics

[](#the-basics)

A `.env` file contains key-value pairs of environment-specific settings. Each line contains a key-value pair. Keys [should](https://www.rfc-editor.org/rfc/rfc2119#section-3) be capitalised, and should only contain A-Z characters and underscores. Thereafter comes an `=` sign, and then the value. See the following example:

```
DB_ENGINE=mysql
DB_NAME=example

```

### Quoted values

[](#quoted-values)

To avoid confusion, you could enclose the value in *double* quotes `"`.

```
DB_PASSWORD="Welkom2018"

```

Note that single quotes `'` are NOT stripped from the value! For example, the value of `DB_TABLE='users'` is `'users'` and not `users`.

### Multi-line values

[](#multi-line-values)

Multi-line values are supported, provided that the value is enclosed in double quotes.

```
TEXT="Calculate density using:

  ρ = m/V

where ρ is the density,
      m is the mass,
  and V is the volume.
"

```

### Special characters

[](#special-characters)

You can use the following special characters in your values:

NameNotationBackslash (`\`)`\\`Double quote (`"`)`\"`Newline`\n`Tab`\t`Example:

```
ESCAPED_VALUES="Escape \t tabs \t, \n newlines \n, and \"quotes\" with a \\backslash\\"

```

### Whitespace handling

[](#whitespace-handling)

Whitespace is handled thus:

- Leading whitespace before keys is ignored.
- Trailing whitespace after values is always trimmed, except when the value including whitespace is enclosed by double quotes.
- Leading whitespace on a newline that is part of the value is honoured.
- Trailing whitespace on a newline that is part of the value is always ignored, except when the line is the last line that is part of the value and the whitespace comes before the closing double quote.

API
---

[](#api)

### `class Socarrat\Environment\EnvironmentManager`

[](#class-socarratenvironmentenvironmentmanager)

#### `static public function getParsedEnv(): array`

[](#static-public-function-getparsedenv-array)

Returns all parsed environment variables as an associative array.

#### `static public function parseFS(string $rootDir, bool $putenv = true)`

[](#static-public-function-parsefsstring-rootdir-bool-putenv--true)

Parses `.env` files from the filesystem.

This method reads the files in the order specified in EnvironmentManager::$fileOrder. You can set this order using [setFileOrder](#static-public-function-setfileorderarray-order-void).

Parameter nameTypeDefault valueDescription`$rootDir``string`-The root directory which contains your `.env` file/s.`$putenv``bool``true`Whether to register the values with PHP's environment, so that they can be retrieved using `getenv()`.#### `static public function parseString(string $envFile, bool $putenv = true)`

[](#static-public-function-parsestringstring-envfile-bool-putenv--true)

Parses a single `.env` file passed as a string.

Parameter nameTypeDefault valueDescription`$envFile``string`-The string to parse`$putenv``bool``true`Whether to register the values with PHP's environment, so that they can be retrieved using `getenv()`.#### `static public function setFileOrder(array $order): void`

[](#static-public-function-setfileorderarray-order-void)

Sets the order (passed as the `$order` parameter) in which `.env` files are loaded. Lower index means higher importance.

The default file order is:

```
[
	".env.local",
	".env.shared",
	".env",
]
```

Testing
-------

[](#testing)

This library is unit-tested by [PHPunit](https://phpunit.de/) using the tests in the [`tests/` directory](./tests/). You can run the test suite on your machine (`composer run-script test`). Test results for each commit (run on Ubuntu 22.04) are available [on GitHub](https://github.com/socarrat-php/environment/actions/workflows/test.yml).

Copyright
---------

[](#copyright)

(c) 2023 Romein van Buren. Licensed under the MIT license.

For the full copyright and license information, please view the [`license.md`](./license.md) file that was distributed with this source code.

###  Health Score

19

—

LowBetter than 10% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 Bus Factor1

Top contributor holds 94.4% 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

1108d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/80e830e4767cfe6a30503054d4b2c80b571bb5e8ec22ceddf28191e8a58f07f0?d=identicon)[Roman1001](/maintainers/Roman1001)

---

Top Contributors

[![garraflavatra](https://avatars.githubusercontent.com/u/34036573?v=4)](https://github.com/garraflavatra "garraflavatra (17 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

dotenvdotenv-parser

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/socarrat-environment/health.svg)

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

###  Alternatives

[composer/composer

Composer helps you declare, manage and install dependencies of PHP projects. It ensures you have the right stack everywhere.

29.4k187.2M2.6k](/packages/composer-composer)[symfony/event-dispatcher

Provides tools that allow your application components to communicate with each other by dispatching events and listening to them

8.6k985.9M3.4k](/packages/symfony-event-dispatcher)[symfony/polyfill-php80

Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions

1.7k815.2M457](/packages/symfony-polyfill-php80)[seld/phar-utils

PHAR file format utilities, for when PHP phars you up

875180.0M32](/packages/seld-phar-utils)[dansmith/laravel5-foundation

Zurb Foundation components for Laravel5

104.6k](/packages/dansmith-laravel5-foundation)

PHPackages © 2026

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