0

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?

Morena
  • 33
  • 7
  • In that case, you will have to boot your application via index.php only. – nice_dev May 24 '22 at 08:19
  • That will mean putting my entire application on the index page and its not possible. I have directories nested inside each other which needs access to the environment variables. – Morena May 24 '22 at 08:30
  • 1
    Booting doesn't mean entire code in single file. You can have a look at how frameworks like Laravel work when they boot. One way for your case is use to session in PHP to get this. Other I can think of is to use a DB table. To optimize the DB approach, you can have a look at Redis. – nice_dev May 24 '22 at 08:36
  • No problem thanks, I will look into that. You are right, I think sessions will also work. Let me try that. But this is just a workaround. Why aren't the variables loaded to the global scope? – Morena May 24 '22 at 08:41
  • They actually are loaded. But if you directly access a script in any nested folder, the code in index.php gets skipped and hence not executed and accessible. You might find this thread relevant to your case. https://stackoverflow.com/questions/14884439/automatically-load-a-config-php-file-for-all-pages-before-anything-else – nice_dev May 24 '22 at 08:46
  • 1
    Alright. I will give it a read. Thanks for your insights . – Morena May 24 '22 at 09:17

0 Answers0