PHPackages                             alzen8work/phpdotenv - 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. alzen8work/phpdotenv

ActiveLibrary

alzen8work/phpdotenv
====================

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

v5.3.0(5y ago)013BSD-3-ClausePHPPHP ^7.1.3 || ^8.0

Since Jan 23Pushed 5y agoCompare

[ Source](https://github.com/alzen8work/phpdotenv)[ Packagist](https://packagist.org/packages/alzen8work/phpdotenv)[ GitHub Sponsors](https://github.com/GrahamCampbell)[ Fund](https://tidelift.com/funding/github/packagist/vlucas/phpdotenv)[ RSS](/packages/alzen8work-phpdotenv/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (7)Versions (88)Used By (0)

PHP dotenv
==========

[](#php-dotenv)

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

[![Banner](https://user-images.githubusercontent.com/2829600/71564012-31105580-2a91-11ea-9ad7-ef1278411b35.png)](https://user-images.githubusercontent.com/2829600/71564012-31105580-2a91-11ea-9ad7-ef1278411b35.png)

[![Software License](https://camo.githubusercontent.com/a42570ff46c0aab2eae7aab733d7b3626edd07f6f3fba921d53ff7bdca889f5e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d425344253230332d2d436c617573652d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Total Downloads](https://camo.githubusercontent.com/a68f30b0888554bddd3de4078868d9293dcf13935b1a071227398784e688befb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f766c756361732f706870646f74656e762e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/vlucas/phpdotenv)[![Latest Version](https://camo.githubusercontent.com/9345bec45824a1996aa40dc1ed0645edde94f3cd48f78e33ed9043deb7364e83/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f766c756361732f706870646f74656e762e7376673f7374796c653d666c61742d737175617265)](https://github.com/vlucas/phpdotenv/releases)

Why .env?
---------

[](#why-env)

**You should never store sensitive credentials in your code**. Storing [configuration in the environment](https://www.12factor.net/config) is one of the tenets of a [twelve-factor app](https://www.12factor.net/). Anything that is likely to change between deployment environments – such as database credentials or credentials for 3rd party services – should be extracted from the code into environment variables.

Basically, a `.env` file is an easy way to load custom configuration variables that your application needs without having to modify .htaccess files or Apache/nginx virtual hosts. This means you won't have to edit any files outside the project, and all the environment variables are always set no matter how you run your project - Apache, Nginx, CLI, and even PHP's built-in webserver. It's WAY easier than all the other ways you know of to set environment variables, and you're going to love it!

- NO editing virtual hosts in Apache or Nginx
- NO adding `php_value` flags to .htaccess files
- EASY portability and sharing of required ENV values
- COMPATIBLE with PHP's built-in web server and CLI runner

PHP dotenv is a PHP version of the original [Ruby dotenv](https://github.com/bkeepers/dotenv).

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

[](#installation)

Installation is super-easy via [Composer](https://getcomposer.org/):

```
$ composer require alzen8work/phpdotenv
```

or add it by hand to your `composer.json` file.

Upgrading
---------

[](#upgrading)

We follow [semantic versioning](https://semver.org/), which means breaking changes may occur between major releases. We have upgrading guides available for V2 to V3, V3 to V4 and V4 to V5 available [here](UPGRADING.md).

Usage
-----

[](#usage)

The `.env` file is generally kept out of version control since it can contain sensitive API keys and passwords. A separate `.env.example` file is created with all the required environment variables defined except for the sensitive ones, which are either user-supplied for their own development environments or are communicated elsewhere to project collaborators. The project collaborators then independently copy the `.env.example` file to a local `.env` and ensure all the settings are correct for their local environment, filling in the secret keys or providing their own values when necessary. In this usage, the `.env`file should be added to the project's `.gitignore` file so that it will never be committed by collaborators. This usage ensures that no sensitive passwords or API keys will ever be in the version control history so there is less risk of a security breach, and production values will never have to be shared with all project collaborators.

Add your application configuration to a `.env` file in the root of your project. **Make sure the `.env` file is added to your `.gitignore` so it is not checked-in the code**

```
S3_BUCKET="dotenv"
SECRET_KEY="souper_seekret_key"
```

Now create a file named `.env.example` and check this into the project. This should have the ENV variables you need to have set, but the values should either be blank or filled with dummy data. The idea is to let people know what variables are required, but not give them the sensitive production values.

```
S3_BUCKET="devbucket"
SECRET_KEY="abc123"
```

You can then load `.env` in your application with:

```
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
```

Optionally you can pass in a filename as the second parameter, if you would like to use something other than `.env`:

```
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__, 'myconfig');
$dotenv->load();
```

All of the defined variables are now available in the `$_ENV` and `$_SERVER`super-globals.

```
$s3_bucket = $_ENV['S3_BUCKET'];
$s3_bucket = $_SERVER['S3_BUCKET'];
```

### Putenv and Getenv

[](#putenv-and-getenv)

Using `getenv()` and `putenv()` is strongly discouraged due to the fact that these functions are not thread safe, however it is still possible to instruct PHP dotenv to use these functions. Instead of calling `Dotenv::createImmutable`, one can call `Dotenv::createUnsafeImmutable`, which will add the `PutenvAdapter` behind the scenes. Your environment variables will now be available using the `getenv` method, as well as the super-globals:

```
$s3_bucket = getenv('S3_BUCKET');
$s3_bucket = $_ENV['S3_BUCKET'];
$s3_bucket = $_SERVER['S3_BUCKET'];
```

### Nesting Variables

[](#nesting-variables)

It's possible to nest an environment variable within another, useful to cut down on repetition.

This is done by wrapping an existing environment variable in `${…}` e.g.

```
BASE_DIR="/var/webroot/project-root"
CACHE_DIR="${BASE_DIR}/cache"
TMP_DIR="${BASE_DIR}/tmp"
```

### Immutability and Repository Customization

[](#immutability-and-repository-customization)

Immutability refers to if Dotenv is allowed to overwrite existing environment variables. If you want Dotenv to overwrite existing environment variables, use `createMutable` instead of `createImmutable`:

```
$dotenv = Dotenv\Dotenv::createMutable(__DIR__);
$dotenv->load();
```

Behind the scenes, this is instructing the "repository" to allow immutability or not. By default, the repository is configured to allow overwriting existing values by default, which is relevant if one is calling the "create" method using the `RepositoryBuilder` to construct a more custom repository:

```
$repository = Dotenv\Repository\RepositoryBuilder::createWithNoAdapters()
    ->addAdapter(Dotenv\Repository\Adapter\EnvConstAdapter::class)
    ->addWriter(Dotenv\Repository\Adapter\PutenvAdapter::class)
    ->immutable()
    ->make();

$dotenv = Dotenv\Dotenv::create($repository, __DIR__);
$dotenv->load();
```

The above example will write loaded values to `$_ENV` and `putenv`, but when interpolating environment variables, we'll only read from `$_ENV`. Moreover, it will never replace any variables already set before loading the file.

By means of another example, one can also specify a set of variables to be allow listed. That is, only the variables in the allow list will be loaded:

```
$repository = Dotenv\Repository\RepositoryBuilder::createWithDefaultAdapters()
    ->allowList(['FOO', 'BAR'])
    ->make();

$dotenv = Dotenv\Dotenv::create($repository, __DIR__);
$dotenv->load();
```

### Requiring Variables to be Set

[](#requiring-variables-to-be-set)

PHP dotenv has built in validation functionality, including for enforcing the presence of an environment variable. This is particularly useful to let people know any explicit required variables that your app will not work without.

You can use a single string:

```
$dotenv->required('DATABASE_DSN');
```

Or an array of strings:

```
$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);
```

If any ENV vars are missing, Dotenv will throw a `RuntimeException` like this:

```
One or more environment variables failed assertions: DATABASE_DSN is missing

```

### Empty Variables

[](#empty-variables)

Beyond simply requiring a variable to be set, you might also need to ensure the variable is not empty:

```
$dotenv->required('DATABASE_DSN')->notEmpty();
```

If the environment variable is empty, you'd get an Exception:

```
One or more environment variables failed assertions: DATABASE_DSN is empty

```

### Integer Variables

[](#integer-variables)

You might also need to ensure that the variable is of an integer value. You may do the following:

```
$dotenv->required('FOO')->isInteger();
```

If the environment variable is not an integer, you'd get an Exception:

```
One or more environment variables failed assertions: FOO is not an integer.

```

One may only want to enforce validation rules when a variable is set. We support this too:

```
$dotenv->ifPresent('FOO')->isInteger();
```

### Boolean Variables

[](#boolean-variables)

You may need to ensure a variable is in the form of a boolean, accepting "true", "false", "On", "1", "Yes", "Off", "0" and "No". You may do the following:

```
$dotenv->required('FOO')->isBoolean();
```

If the environment variable is not a boolean, you'd get an Exception:

```
One or more environment variables failed assertions: FOO is not a boolean.

```

Similarly, one may write:

```
$dotenv->ifPresent('FOO')->isBoolean();
```

### Allowed Values

[](#allowed-values)

It is also possible to define a set of values that your environment variable should be. This is especially useful in situations where only a handful of options or drivers are actually supported by your code:

```
$dotenv->required('SESSION_STORE')->allowedValues(['Filesystem', 'Memcached']);
```

If the environment variable wasn't in this list of allowed values, you'd get a similar Exception:

```
One or more environment variables failed assertions: SESSION_STORE is not an allowed value.

```

It is also possible to define a regex that your environment variable should be.

```
$dotenv->required('FOO')->allowedRegexValues('([[:lower:]]{3})');
```

### Comments

[](#comments)

You can comment your `.env` file using the `#` character. E.g.

```
# this is a comment
VAR="value" # comment
VAR=value # comment
```

### Parsing Without Loading

[](#parsing-without-loading)

Sometimes you just wanna parse the file and resolve the nested environment variables, by giving us a string, and have an array returned back to you. While this is already possible, it is a little fiddly, so we have provided a direct way to do this:

```
// ['FOO' => 'Bar', 'BAZ' => 'Hello Bar']
Dotenv\Dotenv::parse("FOO=Bar\nBAZ=\"Hello \${FOO}\"");
```

This is exactly the same as:

```
Dotenv\Dotenv::createArrayBacked(__DIR__)->load();
```

only, instead of providing the directory to find the file, you have directly provided the file contents.

### Usage Notes

[](#usage-notes)

When a new developer clones your codebase, they will have an additional one-time step to manually copy the `.env.example` file to `.env` and fill-in their own values (or get any sensitive values from a project co-worker).

Security
--------

[](#security)

If you discover a security vulnerability within this package, please send an email to Graham Campbell at . All security vulnerabilities will be promptly addressed. You may view our full security policy [here](https://github.com/vlucas/phpdotenv/security/policy).

License
-------

[](#license)

PHP dotenv is licensed under [The BSD 3-Clause License](LICENSE).

For Enterprise
--------------

[](#for-enterprise)

Available as part of the Tidelift Subscription

The maintainers of `vlucas/phpdotenv` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-vlucas-phpdotenv?utm_source=packagist-vlucas-phpdotenv&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity84

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 74.2% 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 ~34 days

Recently: every ~0 days

Total

87

Last Release

1943d ago

Major Versions

v4.1.8 → 5.0.x-dev2020-07-14

4.1.x-dev → 5.2.x-dev2020-12-03

2.6.x-dev → v3.6.82021-01-20

3.6.x-dev → v4.2.02021-01-20

4.2.x-dev → v5.3.02021-01-20

PHP version history (8 changes)1.0.0PHP &gt;=5.3.2

v2.1.0PHP &gt;=5.3.9

v3.0.0PHP ^5.4 || ^7.0

v4.0.0PHP ^5.5.9 || ^7.0

v2.6.4PHP ^5.3.9 || ^7.0 || ^8.0

v3.6.4PHP ^5.4 || ^7.0 || ^8.0

v4.1.5PHP ^5.5.9 || ^7.0 || ^8.0

v5.0.0PHP ^7.1.3 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/8ab0342edb278600aa6f97fe982e37914ac66bf19b0dea0ef12a65c1b4a116ab?d=identicon)[alzen8work](/maintainers/alzen8work)

---

Top Contributors

[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (368 commits)")[![vlucas](https://avatars.githubusercontent.com/u/187?v=4)](https://github.com/vlucas "vlucas (60 commits)")[![jpuck](https://avatars.githubusercontent.com/u/15305396?v=4)](https://github.com/jpuck "jpuck (8 commits)")[![lucasmichot](https://avatars.githubusercontent.com/u/513603?v=4)](https://github.com/lucasmichot "lucasmichot (6 commits)")[![thedavidmeister](https://avatars.githubusercontent.com/u/629710?v=4)](https://github.com/thedavidmeister "thedavidmeister (6 commits)")[![GabeMedrash](https://avatars.githubusercontent.com/u/8576080?v=4)](https://github.com/GabeMedrash "GabeMedrash (4 commits)")[![Ultrabenosaurus](https://avatars.githubusercontent.com/u/1901532?v=4)](https://github.com/Ultrabenosaurus "Ultrabenosaurus (4 commits)")[![vinkla](https://avatars.githubusercontent.com/u/499192?v=4)](https://github.com/vinkla "vinkla (3 commits)")[![aaemnnosttv](https://avatars.githubusercontent.com/u/1621608?v=4)](https://github.com/aaemnnosttv "aaemnnosttv (3 commits)")[![Korbeil](https://avatars.githubusercontent.com/u/944409?v=4)](https://github.com/Korbeil "Korbeil (3 commits)")[![localheinz](https://avatars.githubusercontent.com/u/605483?v=4)](https://github.com/localheinz "localheinz (3 commits)")[![shuber](https://avatars.githubusercontent.com/u/2419?v=4)](https://github.com/shuber "shuber (3 commits)")[![xjchengo](https://avatars.githubusercontent.com/u/4819996?v=4)](https://github.com/xjchengo "xjchengo (2 commits)")[![alzen8work](https://avatars.githubusercontent.com/u/20431509?v=4)](https://github.com/alzen8work "alzen8work (2 commits)")[![carusogabriel](https://avatars.githubusercontent.com/u/16328050?v=4)](https://github.com/carusogabriel "carusogabriel (2 commits)")[![chapeupreto](https://avatars.githubusercontent.com/u/834048?v=4)](https://github.com/chapeupreto "chapeupreto (2 commits)")[![danmichaelo](https://avatars.githubusercontent.com/u/434495?v=4)](https://github.com/danmichaelo "danmichaelo (2 commits)")[![jrchamp](https://avatars.githubusercontent.com/u/625298?v=4)](https://github.com/jrchamp "jrchamp (2 commits)")[![louim](https://avatars.githubusercontent.com/u/923718?v=4)](https://github.com/louim "louim (2 commits)")[![SergeAx](https://avatars.githubusercontent.com/u/3264530?v=4)](https://github.com/SergeAx "SergeAx (1 commits)")

---

Tags

environmentenvdotenv

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/alzen8work-phpdotenv/health.svg)

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

###  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)[johnathanmiller/secure-env-php

Encrypt environment files for production use.

6054.3k2](/packages/johnathanmiller-secure-env-php)[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)[zepgram/magento-dotenv

Simple autoloader to integrate the Symfony Dotenv component into Magento2

1371.3k](/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.

326.9k](/packages/nystudio107-dotenvy)

PHPackages © 2026

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