PHP getenv always returns false

一世执手 提交于 2020-12-27 06:36:35

问题


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 Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\Dotenv\Exception\PathException;

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?


回答1:


By default, Symfony doesn't use putenv() (I think it's for security reasons, don't remember exactly) so you are not able to use directly getenv() if you are using Symfony's "fake" environment variables.

The best solution in my opinion is to use dependency injection instead. You can access env vars in your Symfony configuration. For example with a yaml configuration file:

framework:
    secret: '%env(APP_SECRET)%'

If you want to be able to use getenv() anyway, that I don't recommand for multiple reasons, you can do this :

  • Before Symfony 5.1 : In your config/bootstrap.php file -> new Dotenv(true)
  • Symfony 5.1 and later : public/index.php, add the following before Dotenv instantation-> Dotenv::usePutenv();

EDIT :

  • Using the putenv PHP function is not thread safe, that's why this setting defaults to false.
  • Didn't notice in the first place your using the Dotenv component as a standalone library, so you can ignore my advice concerning the dependency injection.


来源:https://stackoverflow.com/questions/63813272/php-getenv-always-returns-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!