phppdoenvironment-variables.envphpdotenv

PHP is not reading .env file


I am using PHP with PDO to connect to my database.

I want to start using environment variables, so I used the following terminal command:

composer require vlucas/phpdotenv

My .env file now contains the following values:

DATABASE_HOSTNAME=db
DATABASE_NAME=myDb
DATABASE_USERNAME=user 
DATABASE_PASSWORD=test 

My test db connection file looks like this:

<?php
require_once __DIR__ . "/vendor/autoload.php";

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

$host = getenv("DATABASE_HOSTNAME");
$dbname = getenv("DATABASE_NAME");
$dbuser = getenv("DATABASE_USERNAME");
$dbpass = getenv("DATABASE_PASSWORD");

try{
    $dbc = new PDO("mysql:dbname=$dbname;host=$host;port=3306", $dbuser, $dbpass);
    $dbc->SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch(PDOException $e) {
    echo "Conneciton failed: " . $e->getMessage() . "<br/>";
  }  
?> 

I am getting the below error:

Conneciton failed: SQLSTATE[HY000] [2002] No such file or directory

I added this code to the test db connection file:

echo "X" . getenv('X');
echo "host is " . $host;

In the terminal, I enter: php test.php

And it echos out the following:

Xhost is %

Here is a screenshot:

enter image description here

What am I doing wrong?


Solution

  • This is due to getenv and putenv not being populated by default with the Dotenv library.

    Should use $_ENV instead to read the variables if using the createImmutable function, otherwise check out the docs at https://github.com/vlucas/phpdotenv?tab=readme-ov-file#putenv-and-getenv