php 如何在 Laravel 中动态更改 .env 文件中的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32307426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change variables in the .env file dynamically in Laravel?
提问by Joshua Leung
I want to create a Laravel web app that allows an admin user to change some variables(such as database credentials) in the .env file using the web backend system. But how do I save the changes?
我想创建一个 Laravel Web 应用程序,允许管理员用户使用 Web 后端系统更改 .env 文件中的某些变量(例如数据库凭据)。但是如何保存更改?
回答by lukasgeiter
There is no built in way to do that. If you really want to change the contents of the .env
file, you'll have to use some kind of string replace in combination with PHP's file writing methods. For some inspiration, you should take a look at the key:generate
command: KeyGenerateCommand.php:
没有内置的方法可以做到这一点。如果您真的想更改.env
文件的内容,则必须结合 PHP 的文件写入方法使用某种字符串替换。要获得一些灵感,您应该查看以下key:generate
命令:KeyGenerateCommand.php:
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents($path, str_replace(
'APP_KEY='.$this->laravel['config']['app.key'], 'APP_KEY='.$key, file_get_contents($path)
));
}
After the file path is built and the existence is checked, the command simply replaces APP_KEY=[current app key]
with APP_KEY=[new app key]
. You should be able to do the same string replacement with other variables.
Last but not least I just wanted to say that it might isn't the best idea to let users change the .env file. For most custom settings I would recommend storing them in the database, however this is obviously a problem if the setting itself is necessary to connect to the database.
构建文件路径并检查是否存在后,该命令只需替换APP_KEY=[current app key]
为APP_KEY=[new app key]
. 您应该能够使用其他变量进行相同的字符串替换。
最后但并非最不重要的一点,我只想说让用户更改 .env 文件可能不是最好的主意。对于大多数自定义设置,我建议将它们存储在数据库中,但是如果设置本身是连接到数据库所必需的,这显然是一个问题。
回答by Daniel Camargo
Yet another implementation, in case you have something like:
另一个实现,如果你有类似的东西:
A = B #this is a valid entry
A = B #这是一个有效的条目
In your .env file
在您的 .env 文件中
public function updateEnv($data = array())
{
if (!count($data)) {
return;
}
$pattern = '/([^\=]*)\=[^\n]*/';
$envFile = base_path() . '/.env';
$lines = file($envFile);
$newLines = [];
foreach ($lines as $line) {
preg_match($pattern, $line, $matches);
if (!count($matches)) {
$newLines[] = $line;
continue;
}
if (!key_exists(trim($matches[1]), $data)) {
$newLines[] = $line;
continue;
}
$line = trim($matches[1]) . "={$data[trim($matches[1])]}\n";
$newLines[] = $line;
}
$newContent = implode('', $newLines);
file_put_contents($envFile, $newContent);
}
回答by Phil
Update Erick's answer with consideration of $old
values covering sting, bool and null values.
考虑$old
涵盖 sting、bool 和 null 值的值,更新 Erick 的答案。
public static function changeEnvironmentVariable($key,$value)
{
$path = base_path('.env');
if(is_bool(env($key)))
{
$old = env($key)? 'true' : 'false';
}
elseif(env($key)===null){
$old = 'null';
}
else{
$old = env($key);
}
if (file_exists($path)) {
file_put_contents($path, str_replace(
"$key=".$old, "$key=".$value, file_get_contents($path)
));
}
}
回答by R. Wang
To extend on lukasgeiter's and other's answer above, using regex to match the .env
would be better, , as unlike app.key
, the variable to put in .env
may not be in the config.
为了扩展上面 lukasgeiter 和其他人的答案,使用正则表达式来匹配.env
会更好,因为与 不同app.key
,要放入的变量.env
可能不在配置中。
Below is the code I used when experimenting on custom artisan command. This code generates a key for XChaCha encryption (XCHACHA_KEY=?????
):
下面是我在试验自定义工匠命令时使用的代码。此代码生成 XChaCha 加密的密钥 ( XCHACHA_KEY=?????
):
$path = base_path('.env');
if (file_exists($path)) {
//Try to read the current content of .env
$current = file_get_contents($path);
//Store the key
$original = [];
if (preg_match('/^XCHACHA_KEY=(.+)$/m', $current, $original)) {
//Write the original key to console
$this->info("Original XChaCha key: $original[0]");
//Overwrite with new key
$current = preg_replace('/^XCHACHA_KEY=.+$/m', "XCHACHA_KEY=$b64", $current);
} else {
//Append the key to the end of file
$current .= PHP_EOL."XCHACHA_KEY=$b64";
}
file_put_contents($path, $current);
}
$this->info('Successfully generated new key for XChaCha');
Using preg_match()
allows the original key to be retrieved as needed, also allows the key to be changed even if the actual value is not known.
Usingpreg_match()
允许根据需要检索原始密钥,即使实际值未知,也允许更改密钥。
回答by Erick
I had the same problem and have created the function below
我遇到了同样的问题并创建了下面的函数
public static function changeEnvironmentVariable($key,$value)
{
$path = base_path('.env');
if(is_bool(env($key)))
{
$old = env($key)? 'true' : 'false';
}
if (file_exists($path)) {
file_put_contents($path, str_replace(
"$key=".$old, "$key=".$value, file_get_contents($path)
));
}
}
回答by Siddharth Joshi
/**
* Update Laravel Env file Key's Value
* @param string $key
* @param string $value
*/
public static function envUpdate($key, $value)
{
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents($path, str_replace(
$key . '=' . env($key), $key . '=' . $value, file_get_contents($path)
));
}
}
回答by Niklesh Raut
Another option is using config file instead changing content in .env
file
另一种选择是使用配置文件而不是更改.env
文件中的内容
Put these all in any config files named like newfile.php
inside config
folder. If you actually dont' want to change .evn
content. and treat these all as variable/array element.
将这些全部放在名为newfile.php
insideconfig
文件夹的任何配置文件中。如果您实际上不想更改.evn
内容。并将这些都视为变量/数组元素。
<?php
return [
'PUSHER_APP_ID' => "",
'PUSHER_APP_KEY' => "",
'PUSHER_APP_SECRET' => "",
'PUSHER_APP_CLUSTER' => "",
];
And get/set in controller like below
并在控制器中获取/设置如下所示
config(['newfile.PUSHER_APP_ID' => 'app_id_value']);//set
config('newfile.PUSHER_APP_ID');//get