Loads environment variables from .env
to getenv()
, $_ENV
and $_SERVER
automagically.
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 5.4'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 is super-easy via Composer:
$ composer require vlucas/phpdotenv
or add it by hand to your composer.json
file.
Version 4 sees some refactoring, and support for escaping dollars in values
(vlucas#380). It is no longer possible to
change immutability on the fly, and the Loader
no longer is responsible for
tracking immutability. It is now the responsibility of "repositories" to track
this. One must explicitly decide if they want (im)mutability when constructing
an instance of Dotenv\Dotenv
.
For more details, please see the release notes and the upgrading guide.
New in Version 3 is first-class support for multiline variables
(#301) and much more
flexibility in terms of which parts of the environment we try to read and
modify (#300). Consequently,
you will need to replace any occurrences of new Dotenv(...)
with
Dotenv::create(...)
, since our new native constructor takes a Loader
instance now, so that it can be truly customized if required. Finally, one
should note that the loader will no longer be trimming values
(#302), moreover
Loader::load()
and its callers now return an associative array of the
variables loaded with their values, rather than an array of raw lines from the
environment file (#306).
For more details, please see the release notes and the upgrading guide.
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 accessible with the getenv
method, and are available in the $_ENV
and $_SERVER
super-globals.
$s3_bucket = getenv('S3_BUCKET');
$s3_bucket = $_ENV['S3_BUCKET'];
$s3_bucket = $_SERVER['S3_BUCKET'];
You should also be able to access them using your framework's Request class (if you are using a framework).
$s3_bucket = $request->env('S3_BUCKET');
$s3_bucket = $request->getEnv('S3_BUCKET');
$s3_bucket = $request->server->get('S3_BUCKET');
$s3_bucket = env('S3_BUCKET');
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 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 relevent if one is calling the "create" method
using the RepositoryBuilder
to construct a more custom repository:
$repository = Dotenv\Repository\RepositoryBuilder::create()
->withReaders([
new Dotenv\Repository\Adapter\EnvConstAdapter(),
])
->withWriters([
new Dotenv\Repository\Adapter\EnvConstAdapter(),
new Dotenv\Repository\Adapter\PutenvAdapter(),
])
->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.
Using Dotenv, you can require specific ENV vars to be defined ($_ENV, $_SERVER or getenv()) - throws an exception otherwise. Note: It does not check for existence of a variable in a '.env' file. 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
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
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
You may need to ensure a variable is in the form of a boolean, accepting "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
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})');
You can comment your .env
file using the #
character. E.g.
# this is a comment
VAR="value" # comment
VAR=value # comment
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).
If you discover a security vulnerability within this package, please send an email to Graham Campbell at graham@alt-three.com. All security vulnerabilities will be promptly addressed. You may view our full security policy here.
PHP dotenv is licensed under The BSD 3-Clause License.
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.