user3871
user3871

Reputation: 12718

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_dumping 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:

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?

Upvotes: 10

Views: 28835

Answers (3)

Mr. J
Mr. J

Reputation: 1839

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'];

In New Version:

require 'vendor/autoload.php';
    
# $dotenv = new Dotenv\Dotenv(__DIR__);
# Replaced by following line
$dotEnv = Dotenv\Dotenv::createImmutable(__DIR__);
# and then rest of code as normal
$dotenv->load();

$DB_HOST = $_ENV['DB_HOST'];

Upvotes: 17

Md Jahid Khan Limon
Md Jahid Khan Limon

Reputation: 341

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');

Upvotes: 9

alexb
alexb

Reputation: 11

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.

Upvotes: 1

Related Questions