• Stars
    star
    12,894
  • Rank 2,329 (Top 0.05 %)
  • Language
    PHP
  • License
    BSD 3-Clause "New...
  • Created over 11 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

PHP dotenv

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

Banner

Software License Total Downloads Latest Version

Why .env?

You should never store sensitive credentials in your code. Storing configuration in the environment is one of the tenets of a twelve-factor app. 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.

Installation

Installation is super-easy via Composer:

$ composer require vlucas/phpdotenv

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

Upgrading

We follow semantic versioning, 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.

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();

To suppress the exception that is thrown when there is no .env file, you can:

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

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

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

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 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

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

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

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

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

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

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

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

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

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).

Troubleshooting

In certain server setups (most commonly found in shared hosting), PHP might deactivate superglobals like $_ENV or $_SERVER. If these variables are not set, review the variables_order in the php.ini file. See php.net/manual/en/ini.core.php#ini.variables-order.

Security

If you discover a security vulnerability within this package, please send an email to [email protected]. All security vulnerabilities will be promptly addressed. You may view our full security policy here.

License

PHP dotenv is licensed under The BSD 3-Clause License.

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.

More Repositories

1

valitron

Valitron is a simple, elegant, stand-alone validation library with NO dependencies
PHP
1,552
star
2

frisby

Frisby is a REST API testing framework built on Jest that makes testing API endpoints easy, fast, and fun.
JavaScript
1,515
star
3

bulletphp

A resource-oriented micro PHP framework
PHP
417
star
4

phpDataMapper

Object-Oriented PHP5 DataMapper ORM
PHP
118
star
5

pikirasa

PKI public/private RSA key encryption using the OpenSSL extension
PHP
102
star
6

devdata.io

The Data You Need, The Programming Language You Want
HTML
76
star
7

Spot

[DEPRECATED - use v2] Simple DataMapper ORM for PHP 5.3+
PHP
75
star
8

sheetquery

Query Builder/ORM for Google Sheets
TypeScript
71
star
9

vlid

Lightweight validation library with NO dependencies. A nice Joi alternative with a similar API.
JavaScript
63
star
10

universal-react-helloworld

Simplest possible starting point for using universal/isomorphic React.js + Node.js + Express.js
JavaScript
42
star
11

dos-css

DOS-Style CSS for retro fun
HTML
24
star
12

hyperspan

Build a Hypermedia API response once and return it in multiple formats
PHP
18
star
13

gasmask

Mocks for Google Apps Script libraries, specifically around Spreadsheets
TypeScript
16
star
14

toystore

Lightweight central store of state with the ability to watch for and react to specific property changes
JavaScript
15
star
15

bulletphp-skeleton

Skeleton example app using Bullet with templates and error handling
PHP
9
star
16

jsx-tmpl

Stop transpiling React components for Node. Use native ES6 template literals that output JSX instead!
JavaScript
8
star
17

turbolinks-demo-node

Copy of the Ruby Turbolinks Demo app in Node.js
HTML
6
star
18

toystore-react

React bindings for toystore (central store of state)
JavaScript
5
star
19

echotag

Super simple ES6 tagged template function for printing an HTML string
JavaScript
5
star
20

nudos

Heavily retro/DOS-inspired CSS while still modern enough to use
HTML
4
star
21

brightbudget-web

Demo web app API for a Hypermedia API presentation that powers brightbudget-app
JavaScript
4
star
22

presentation-slides-you-dont-know-nodejs

Presentation Slides for "You Don't Know Node.js"
CSS
4
star
23

jTreePlus

jTree with modifications to allow clickable links and form elements within tree nodes
JavaScript
3
star
24

jsx-native

Build JSX using native ES6 templates. No transpiling required for Node.js and modern browsers.
JavaScript
3
star
25

dotfiles-old

Personal dotfiles - mainly for ZSH and Vim configurations
Vim Script
3
star
26

phpunit-gearman-testing

Exploratory project on possible ways to test Gearman jobs using PHPUnit
PHP
3
star
27

brightbudget-app

Demo app for Hypermedia API presentation
JavaScript
3
star
28

spot-site

Spot DataMapper Website
HTML
2
star
29

example-browser-debugging

JavaScript
2
star
30

frisby-site

Main website for Frisby.js with documentation
2
star
31

dotfiles-old-fresh

Vance's dotfiles managed by fresh
Shell
1
star
32

titanium-example-basic-counter

Example Titanium app with simple single-model binding to increment a counter
JavaScript
1
star
33

twicebreaker

Icebreaker game with the Twilio API
PHP
1
star
34

titemplate

Appcelerator Titanium template I use to start new projects - with coffeescript, Jade, a TSS reset, and other goodies
JavaScript
1
star
35

startuporpharma.com

Is it a startup, or a pharmaceutical drug?
JavaScript
1
star
36

presentation-slides-js-browser-debugging

Presentation Slides for "Effective JavaScript Browser Debugging"
CSS
1
star
37

bulletphp-site

Main BulletPHP Website
PHP
1
star
38

budgetsheet-website-static-html

BudgetSheet Website
HTML
1
star
39

skycap

Drop-in authentication and authoriztion framework for Express.js
JavaScript
1
star
40

swagjs-site

Initial splash page signup site for JavaScript blocks
HTML
1
star
41

openx-oauth-client

Modern PHP client for working with the OpenX v4 oAuth API
PHP
1
star
42

titanium-chartjs-example

Example App with Chart.js Example in WebView
JavaScript
1
star
43

bulletphp-blog-example

Obligatory Blog Example built with the Bullet PHP Microframework
PHP
1
star