I am currently using vlucas/phpdotenv to load environment variables in my pure php application. I installed the package with composer then loaded it in the index page like:
//Load Composer's auto loader
require_once realpath(__DIR__ . '/vendor/autoload.php');
//load .env
$dotenv = \Dotenv\Dotenv::createUnsafeImmutable(__DIR__);
$dotenv->load();
This works just fine. I can even retrieve values of the environment variables and display them.
//retrieve host
$host = $_ENV["DB_HOST"];
echo $host;
The above code outputs the value stored in that environment variable. However, this only works in the index.php page where the package is instantiated. If I put the same code snippet in a different php page I get a warning that DB_HOST is an undefined index. Even:
getenv("DB_HOST");
returns a blank. What I am missing here? I do not believe that I have to load the package in every page where I utilized environment variables. So, how do I load my environment variables only once and access them on the global scope?