我有一个简单的 Symfony 项目,在 composer.json 中使用 "symfony/dotenv": "4.3.*", 并尝试读取一个环境变量.
I have a simple Symfony project, using "symfony/dotenv": "4.3.*", in the composer.json and trying to read in the value of an environment variable.
这是我的命令:
var_dump($_ENV['MY_NEW_VAR']);这是我的.env文件
MY_NEW_VAR=testing执行命令后,我得到以下内容
Upon executing the command I get the following
string(7) "testing"到目前为止一切都很好......但是现在如果我想使用环境变量来覆盖设置它会返回一个错误.首先我设置环境变量
All good so far.... But now if I want to use environment variables to override the setting it returns an error. First I set the environment variable
export MY_NEW_VAR="something_else"然后再次执行命令,结果如下
Then execute the command again, with the following results
[ErrorException] Notice: Undefined index: MY_NEW_VAR如果我使用 unset MY_NEW_VAR 删除环境变量并再次执行命令,我会从 .env 文件中获取值
If I remove the environment variable using unset MY_NEW_VAR and execute the command again I get the value from the .env file
我希望环境变量覆盖 .env 设置,如 .env 文件的注释中所述
I would expect the environment variable to override the .env setting as explained in the comments of the .env file
# In all environments, the following files are loaded if they exist, # the later taking precedence over the former: # # * .env contains default values for the environment variables needed by the app # * .env.local uncommitted file with local overrides # * .env.$APP_ENV committed environment-specific defaults # * .env.$APP_ENV.local uncommitted environment-specific overrides # # Real environment variables win over .env files.为什么它不适用于环境变量?我错过了什么吗?
Why does it not work with environment variables? Am I missing something?
推荐答案您问题中的代码是正确的,所以我打赌问题出在其他地方.
The code in your question is correct, so I'd wager the problem lies somewhere else.
getenv()、$_ENV 和 $_SERVER 的工作方式有很多变幻莫测和不一致的地方.根据我的经验,我发现 $_SERVER 更可靠,而且很多时候同时检查两者更安全.例如.如果您检查 Symfony 4.3 的 config/bootstrap.php 上的代码,您将看到如下内容:
There are many vagaries and inconsistencies about how getenv(), $_ENV and $_SERVER work. I have found $_SERVER to be more reliable in my experience, and many times it safer to check both. E.g. if you check the code on config/bootstrap.php for Symfony 4.3 you'll see stuff like this:
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';无论如何,如果您的 $_ENV 超全局变量最初是空的,那可能是因为 variables_order 设置.检查其值,如果不包含 E,请将其添加到现有值中,并正确填充它.
In any case, if your $_ENV superglobal is initially empty, it could be because on the variables_order setting. Check its value, and if doesn't include an E, prepend it to the existing value and with that it should be populated correctly.
文档 说S 等价于 ES...
在 CGI 和 FastCGI SAPI 中,$_SERVER 也由环境中的值填充;无论 E 在该指令中的其他位置放置如何,S 始终等同于 ES.
In both the CGI and FastCGI SAPIs, $_SERVER is also populated by values from the environment; S is always equivalent to ES regardless of the placement of E elsewhere in this directive.
但我没有发现它一直如此.
but I have not found it to be consistently so.
更多推荐
无法读取环境变量
发布评论