'PHP DOTENV unable to load env vars
I'm using php dotenv for env vars for my php application.
The readme says I can load php dotenv
into my application with:
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
When I try to login, I get a 500 error. I tried var_dump
ing my $dotenv
var to see what it contains but I get nothing. Am I including this incorrectly?
/php/DbConnect.php:
<?php
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$DB_HOST = getenv('DB_HOST');
$DB_USERNAME = getenv('DB_USERNAME');
$DB_PASSWORD = getenv('DB_PASSWORD');
$DB_DATABASE = getenv('DB_DATABASE');
My root/composer.json file:
{
"require": {
"vlucas/phpdotenv": "^2.0"
}
}
My phpdotenv vendor files are:
- root/vendor/vlucas/phpdotenv/src/Dotenv.php
- root/vendor/vlucas/phpdotenv/src/Loader.php
- root/vendor/vlucas/phpdotenv/src/Validator.php
In my root/php/DbConnect.php file:
<?php
require 'vendor/autoload.php';
require 'vendor/vlucas/phpdotenv/src/Dotenv.php';
require 'vendor/vlucas/phpdotenv/src/Loader.php';
require 'vendor/vlucas/phpdotenv/src/Validator.php';
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$DB_HOST = getenv('DB_HOST');
...
Am I including correctly?
Solution 1:[1]
Note that the docs for DotENV don't recommend using getenv()
or putenv()
. Instead, you should use $_ENV['EXAMPLEVAR']
So this is now the correct way:
require 'vendor/autoload.php';
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$DB_HOST = $_ENV['DB_HOST'];
Solution 2:[2]
I know this is 6 months old, but you do not need include/require as "phpdotenv" is loading Dotenv namespace. Check in vendor directory in composer directory what is auto loaded.
So all what you need is:
require 'vendor/autoload.php';
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
$DB_HOST = getenv('DB_HOST');
Also make sure that load() method can find your .env file, if named differently, pass the name of the file to the load() method. Check docs here: https://github.com/vlucas/phpdotenv under Usage section.
Solution 3:[3]
Using getenv
and putenv
are not thread safe. You should use $_ENV['DB_HOT']
or $_SERVER['DB_HOST']
. However, if you still need to use these functions, You can use createUnsafeImmutable
static method. So the code will be
$dotenv = Dotenv\Dotenv::createUnsafeImmutable(__DIR__);
$dotenv->load();
$DB_HOST = getenv('DB_HOST');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | alexb |
Solution 3 | Md Jahid Khan Limon |