我想创建一个Laravel应用程序,允许管理用户使用web后端系统更改.env文件中的一些变量(例如数据库凭据)。但是我该如何保存这些变化呢?
发布于 2015-08-31 09:27:54
没有任何办法可以做到这一点。如果您真的想要更改.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)
));
}在构建了文件路径并检查了是否存在之后,该命令只需将APP_KEY=[current app key]替换为APP_KEY=[new app key]。您应该能够用其他变量替换相同的字符串。
最后,但同样重要的是,我只想说,让用户更改.env文件可能不是最好的主意。对于大多数自定义设置,我建议将它们存储在数据库中,但是如果设置本身是连接数据库所必需的,那么这显然是一个问题。
发布于 2017-06-09 02:47:33
还有另一个实现,如果您有这样的东西:
A=B#这是一个有效的条目
在.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);
}发布于 2018-01-09 14:07:28
更新Erick的答案,考虑$old值,包括sting、bool和null值。
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)
));
}
}https://stackoverflow.com/questions/32307426
复制相似问题