sajad torkamani

Why use environment variables?

When building web applications or command-line scripts, you often need to specify sensitive configuration values in your code. These can be MySQL database credentials, SMTP credentials, or any third-party API credentials.

Instead of hardcoding these values in your source code, it’s often a good idea to store them in a .env file and not track this file in Git. This gives you several benefits:

  • You can use different configuration values in different environments. For example, you may use a different AWS S3 bucket in development versus production.
  • Sensitive credentials won’t be accessible to anyone who manages to gain unauthorized access to your Git repository.
  • Sensitive credentials such as the production database credentials do not have to be shared with all the project collaborators.

The vlucas/phpdotenv package helps you easily use .env files in your code.

Okay, how?

Install the vlucas/phpdotenv package using composer:

composer require vlucas/phpdotenv

Create a .env.example file with placeholders for all the environment variables you want to use. You can track this file in Git and so make it easier for developers in your team to know what values are needed. You can even specify default values for non-sensitive credentials.


Create a .env file using .env.example as a template and fill in the actual values. For example:


Load variables from .env file in the current directory:

# Change path to vendor/autoload.php as needed
require_once 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);

# Use env variables
echo $_ENV['S3_REGION']; # eu-west-2
echo $_ENV['S3_BUCKET']; # my-bucket-123

See the vlucas/phpdotenv docs for more info.

Restrict access to .env files

You’ll want to configure your webserver (e.g., Nginx or Apache) to deny access to the .env file. In Nginx, the following config should do the trick.

server {
  # Usual configuration...

  location ~ /\.env {
    deny all;
Tagged: PHP