sajad torkamani

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

Instead of hardcoding these values in our 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 us several benefits:

  • We can use different configuration values in different environments. For example, we may use a different AWS S3 bucket in development vs production.
  • Sensitive credentials won't be accessible to anyone who manages to gain unauthorized access to our Git repository.
  • Highly sensitive credentials such as the production database credentials do not have to be shared with all the project collaborators.

The vlucas/phpdotenv package helps us 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.

S3_REGION=
S3_BUCKET=

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

S3_REGION=eu-west-2
S3_BUCKET=my-bucket-123

Load variables from .env file in the current directory:

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

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

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

Tagged: PHP