phpenvironment-variables

Load a .env file with PHP


I'm currently coding on a pure PHP project and I need to load an .env file to get some variables. After a bit of searching I turned to the vlucas/phpdotenv plugin (That I imported with Composer), but I can't import it! Do I have to use an MVC model for this to work?

index.php:

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

bdd.php:

<?php

    function DBConnect() {
        $user = getenv("DB_USER");
        $pass = $_ENV["DB_PASSWORD"];


Solution

  • You forgot to add require_once realpath(__DIR__ . '/vendor/autoload.php'); to your index.php

    .env

    USER_NAME='jfBiswajit'
    

    index.php

    <?php
    
    require_once realpath(__DIR__ . '/vendor/autoload.php');
    
    // Looing for .env at the root directory
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
    $dotenv->load();
    
    // Retrive env variable
    $userName = $_ENV['USER_NAME'];
    
    echo $userName; //jfBiswajit