PHP getenv always returns false

The getenv() always returns false. I am using Symfony dotenv library and loading my variables from a .env file in the root of my project.

use SymfonyComponentDotenvDotenv;
use SymfonyComponentDotenvExceptionPathException;

if (!getenv('APP_ENV')) {
    try {
        (new Dotenv())->load(__DIR__ . '/../.env');
    } catch (PathException $ex) {
        echo $ex->getMessage();
        exit(1);
    }
}

var_dump(getenv('APP_ENV')); // bool(false)

But when I dump the super global I can see my variables

var_dump($_ENV); // array:1["APP_ENV" => "dev"]

So what am I missing?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 1

Your email address will not be published. Required fields are marked *


Holger

Holger

We encountered the same issue (with Symfony 5.1.7). Doing getenv(‘SOME_VARIABLE’) always returns false, doing $_ENV[‘SOME_VARIABLE’] returns the value of ‘SOME_VARIABLE’ as per our .env or .env.local file. That’s with “symfony/dotenv v5.0.11”.

Apparently, symfony/dotenv made a change some time ago, to no longer support putenv() and getenv() by default, because these PHP functions are not thread safe. See these references:

* https://github.com/symfony/dotenv/commit/d2fa94d2 (10 Apr 2019)
* https://github.com/symfony/symfony/pull/29131
* https://github.com/symfony/symfony/pull/33357
* https://github.com/symfony/symfony/commit/d67289ca
* https://github.com/symfony/symfony/commit/f48f19db

You should either change getenv() to $_ENV[] everywhere in your code, or as a short-term-solution, in your Symfony config/bootstrap.php or public/index.php change “new Dotenv()” to “new Dotenv(true)”.