phpdotenv is made for development environments, and generally should not be used in production. In production, the actual environment variables should be set so that there is no overhead of loading the .env file on each request. This can be achieved via an automated deployment process with tools like Vagrant, chef, or Puppet, or can be set manually with cloud hosts like Pagodabox and Heroku.

The .env file is meant to be a convenience to make things easier to change in local development environments.

Using the technique described here, the exact same $_ENV superglobal gets set with your environmental variables, and are made available via the same getenv() function. The difference is that your webserver or CLI sets the variables directly, without having to parse the .env file.

Without question, this is a micro-optimization... and is unlikely to make a significant performance difference. But why add overhead for no reason?

Using Dotenvy

From your project's root directory that contains the .env and /vendor directory, do:

vendor/bin/dotenvy

If you're on Windows, do:

vendor/bin/dotenvy.bat

If your .env file lives somewhere else, you can pass in the directory to the .env file:

vendor/bin/dotenvy /path/to/some/dir/

Then do not create a .env file on your production environment, instead paste or insert via a deployment system the resulting file that Dotenvy generates for you.

In this way, the appropriate .env variables will be automatically injected by your Apache server, or Nginx server, or via CLI.

This means that the .env file no longer needs to be parsed on every request.

Updating .gitignore

Make sure you .gitignore all of the .env* files with a line like this in your root project .gitignore file:

.env*

...to ensure that none of your secrets in the generated .env* files are checked into git. Note the trailing *

Example .env file

Given a .env file that looks like this:

# The environment Craft is currently running in ('dev', 'staging', 'production', etc.)
ENVIRONMENT="local"# The secure key Craft will use for hashing and encrypting data
SECURITY_KEY="jMgCxHuaM1g3qSzHiknTt5S8gDy5BNW7"# The database driver that will be used ('mysql' or 'pgsql')
DB_DRIVER="mysql"# The database server name or IP address (usually this is 'localhost' or '127.0.0.1')
DB_SERVER="localhost"# The database username to connect with
DB_USER="homestead"# The database password to connect with
DB_PASSWORD="secret"# The name of the database to select
DB_DATABASE="craft3"# The database schema that will be used (PostgreSQL only)
DB_SCHEMA="public"# The prefix that should be added to generated table names (only necessary if multiple things are sharing the same database)
DB_TABLE_PREFIX=""# The port to connect to the database with. Will default to 5432 for PostgreSQL and 3306 for MySQL.
DB_PORT="3306"

The following files will be output in the same directory as the .env file: