Download the PHP package vlucas/phpdotenv without Composer

On this page you can find all versions of the php package vlucas/phpdotenv. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?
vlucas/phpdotenv
Rate from 1 - 5
Rated 4.85 based on 27 reviews

Informations about the package phpdotenv

PHP dotenv

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

Banner

Total Downloads Latest Version

**Special thanks to [our sponsors](https://github.com/sponsors/GrahamCampbell)**

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!

PHP dotenv is a PHP version of the original Ruby dotenv.

Installation

Installation is super-easy via Composer:

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

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.

You can then load .env in your application with:

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

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

Both the directory and the file name may also be given as arrays, in which case only the first readable file found is loaded. To merge every readable file instead, with later files overriding earlier ones, pass false as the third parameter. The file encoding may be specified using the fourth parameter:

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

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 (or Dotenv::createUnsafeMutable instead of Dotenv::createMutable), 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:

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.

Nested references must use the ${…} syntax: a bare $BASE_DIR is never interpolated. Interpolation happens in unquoted and double-quoted values, but never inside single-quoted ones, and inside double quotes a reference can be escaped by writing \${BASE_DIR}. If a referenced variable is not defined, the reference is left in place verbatim rather than being replaced by an empty string. References are resolved from right to left, so a resolved inner reference can itself form part of an outer one. Resolution reads from the repository being loaded into, so when using createImmutable, a variable already present in $_SERVER or $_ENV takes precedence over the value defined in your file, and when using createUnsafeImmutable, values visible through getenv() and putenv() are read and protected as well.

Quoting and Escaping

Values may be unquoted, single-quoted or double-quoted. Single-quoted values are treated completely literally: no escape sequences are recognised, and no variables are interpolated. Backslashes in unquoted values are also treated literally. Inside double quotes, exactly the escape sequences \", \\, \$, \f, \n, \r, \t and \v are recognised, with the character escapes producing their real control characters, and any other backslash sequence is a parse error, so a double-quoted Windows path must use doubled backslashes (or be single-quoted instead):

Only double-quoted values may span multiple lines:

A double-quoted value left unterminated at the end of the file is currently discarded silently, along with any lines that follow it. A line consisting of just a variable name with no equals sign will clear that variable from the environment when loading in mutable mode.

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:

A variable counts as existing if it is set in any of the repository's adapters, including values only present in $_SERVER, and once one immutable instance has loaded a variable, a second instance will treat it as existing too. Within a single load, however, an instance may overwrite a variable it wrote itself, which is how later files in a merge override earlier ones. The array returned by load() contains only the variables that were actually written, so variables skipped due to immutability are omitted. For validation or testing without touching the real environment, use createArrayBacked.

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:

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:

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:

Or an array of strings:

If any ENV vars are missing, Dotenv will throw a Dotenv\Exception\ValidationException like this:

Empty Variables

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

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

Integer Variables

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

Note that only unsigned digit strings pass this check: signed values such as -5 or +5 are rejected. If the environment variable is not an integer, you'd get an Exception:

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

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", case-insensitively and ignoring surrounding whitespace. This check requires the filter extension. You may do the following:

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

Similarly, one may write:

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:

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

It is also possible to define a regex that your environment variable should be. The regex is applied as an unanchored match, so it succeeds if any part of the value matches; anchor the pattern to match the whole value.

Comments

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

A # begins a comment anywhere outside of quotes, even when it directly follows an unquoted value, so any value that should contain a # must be quoted:

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:

This is much the same as:

only, instead of providing the directory to find the file, you have directly provided the file contents. Note that nested variables are resolved against only the variables already defined earlier in the given string, so parse cannot read values from your real environment.

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.


All versions of phpdotenv with dependencies

PHP Build Version
Package Version
Requires php Version ^7.2.5 || ^8.0
ext-pcre Version *
graham-campbell/result-type Version ^1.2
phpoption/phpoption Version ^1.10
symfony/polyfill-ctype Version ^1.26
symfony/polyfill-mbstring Version ^1.26
symfony/polyfill-php80 Version ^1.26
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package vlucas/phpdotenv contains the following files

Loading the files please wait ...