问题
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