sajad torkamani

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 approach gives you several benefits:

The <a rel="noreferrer noopener" href="" data-type="URL" data-id="" target="_blank">vlucas/phpdotenv</a> package helps you easily use .env files in our code.

Download 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 <a rel="noreferrer noopener" href="" data-type="URL" data-id="" target="_blank">vlucas/phpdotenv</a> 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;