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:

The <a href="https://github.com/vlucas/phpdotenv" data-type="URL" data-id="https://github.com/vlucas/phpdotenv" target="_blank" rel="noreferrer noopener">vlucas/phpdotenv</a> 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 <a href="https://github.com/vlucas/phpdotenv" data-type="URL" data-id="https://github.com/vlucas/phpdotenv" target="_blank" rel="noreferrer noopener">vlucas/phpdotenv</a> docs for more info.