0

I'm using WAMP, with PHP 7.3. To get the environment variables, i'm using the PHP dotenv package. I am getting the following error when I reload the page too often / too fast.

error

The databaseConnector.php

<?php
namespace App\Common;

class DatabaseConnector{
    public static function getConnection(){

        $drive = $_ENV['DB_DRIVE'];
        $host = $_ENV['DB_HOST'];
        $port = $_ENV['DB_PORT'];
        $db = $_ENV['DB_NAME'];
        $user = $_ENV['DB_USER'];
        $pass = $_ENV['DB_PASS'];

        try{
            return new \PDO($drive.':host='.$host.'; port='.$port.'; dbname='.$db, $user, $pass);
        } catch (\PDOException $e){
            exit($e->getMessage());
        }
    }
}

When I access the page normally, this error does not occur. What might be causing this?

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
Felipe Ribeiro
  • 191
  • 1
  • 1
  • 7
  • 2
    What have you tried to resolve the problem? Where are you stuck? The code does not show where you define the environment variables – Nico Haase Nov 13 '21 at 09:09
  • Maybe interesting? [Why is my $_ENV empty?](https://stackoverflow.com/questions/3780866/why-is-my-env-empty) – Ryan Vincent Nov 13 '21 at 13:54

1 Answers1

0
<?php
namespace App\Common;

class DatabaseConnector{
    public static function getConnection(){
        GLOBAL $_ENV; // add this line
        $drive = $_ENV['DB_DRIVE'];
        $host = $_ENV['DB_HOST'];
        $port = $_ENV['DB_PORT'];
        $db = $_ENV['DB_NAME'];
        $user = $_ENV['DB_USER'];
        $pass = $_ENV['DB_PASS'];

        try{
            return new \PDO($drive.':host='.$host.'; port='.$port.'; dbname='.$db, $user, $pass);
        } catch (\PDOException $e){
            exit($e->getMessage());
        }
    }
}
sepordeh
  • 62
  • 4
  • Please add some explanation to your answer such that others can learn from it. What did you change, and why? How does your change explain that the code works sometimes, and fails at other times? – Nico Haase Nov 13 '21 at 09:53
  • 2
    Also, according to https://www.php.net/manual/en/language.variables.superglobals.php, `$_ENV` is available everywhere without using `global` – Nico Haase Nov 13 '21 at 09:54