Load Environment Variables From .env File using PHP

.env

HOST=localhost

symfony/dotenv library

  1. Add symfony/dotenv library to composer.json file:
"require": {
    "symfony/dotenv": "^5.0"
}
  1. Install library from the command line:
composer install
  1. Load environment variables from .env file:
<?php

use Symfony\Component\Dotenv\Dotenv;

require_once __DIR__.'/vendor/autoload.php';

$path = __DIR__.'/.env';
$dotenv = new Dotenv();
$dotenv->load($path);

$envVar = $_ENV['HOST'];

echo $envVar; // localhost

Leave a Comment

Cancel reply

Your email address will not be published.