Php 如何在Laravel中动态更改.env文件中的变量?
我想创建一个Laravel web应用程序,允许管理员用户使用web后端系统更改.env文件中的一些变量(例如数据库凭据)。但是如何保存更改?没有内置的方法来保存更改。如果您真的想更改Php 如何在Laravel中动态更改.env文件中的变量?,php,laravel,Php,Laravel,我想创建一个Laravel web应用程序,允许管理员用户使用web后端系统更改.env文件中的一些变量(例如数据库凭据)。但是如何保存更改?没有内置的方法来保存更改。如果您真的想更改.env文件的内容,则必须结合使用某种字符串替换和PHP的文件编写方法。要获得一些灵感,您应该看看键:generate命令: 在构建文件路径并检查存在性之后,该命令只需将APP\u KEY=[current APP KEY]替换为APP\u KEY=[new APP KEY]。您应该能够用其他变量替换相同的字符串。
.env
文件的内容,则必须结合使用某种字符串替换和PHP的文件编写方法。要获得一些灵感,您应该看看键:generate
命令:
在构建文件路径并检查存在性之后,该命令只需将APP\u KEY=[current APP KEY]
替换为APP\u KEY=[new APP KEY]
。您应该能够用其他变量替换相同的字符串。最后但并非最不重要的一点,我只是想说,让用户更改.env文件可能不是最好的主意。对于大多数自定义设置,我建议将它们存储在数据库中,但是如果连接到数据库需要设置本身,则这显然是一个问题。我也遇到了同样的问题,并创建了下面的函数
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)
));
}
}
还有另一个实现,如果您有以下情况: 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);
}
更新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)
));
}
}
另一个选项是使用配置文件,而不是更改
.env
文件中的内容
将这些文件放在config
文件夹中名为newfile.php
的任何配置文件中。如果您确实不想更改.evn
内容。并将它们全部视为变量/数组元素
<?php
return [
'PUSHER_APP_ID' => "",
'PUSHER_APP_KEY' => "",
'PUSHER_APP_SECRET' => "",
'PUSHER_APP_CLUSTER' => "",
];
要扩展lukasgeiter和其他人的上述答案,使用正则表达式匹配
.env
会更好,因为与app.key
不同,要放入.env
的变量可能不在配置中
下面是我在试验自定义artisan命令时使用的代码。此代码为XChaCha加密生成密钥(XChaCha\u key=?????
):
使用
preg_match()
可以根据需要检索原始密钥,也可以更改密钥,即使实际值未知。$old可能在我的窗口环境中未定义失败。任何解决方案。当我调试$this->laravel['config']时出现错误
它说错误评估代码谢谢,它节省了我的时间。最好在答案中添加解释,而不是代码。
/**
* @param string $key
* @param string $val
*/
protected function writeNewEnvironmentFileWith(string $key, string $val)
{
file_put_contents($this->laravel->environmentFilePath(), preg_replace(
$this->keyReplacementPattern($key),
$key . '=' . $val,
file_get_contents($this->laravel->environmentFilePath())
));
}
/**
* @param string $key
* @return string
*/
protected function keyReplacementPattern(string $key): string
{
$escaped = preg_quote('=' . env($key), '/');
return "/^" . $key . "{$escaped}/m";
}
<?php
return [
'PUSHER_APP_ID' => "",
'PUSHER_APP_KEY' => "",
'PUSHER_APP_SECRET' => "",
'PUSHER_APP_CLUSTER' => "",
];
config(['newfile.PUSHER_APP_ID' => 'app_id_value']);//set
config('newfile.PUSHER_APP_ID');//get
$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');
/**
* @param string $key
* @param string $val
*/
protected function writeNewEnvironmentFileWith(string $key, string $val)
{
file_put_contents($this->laravel->environmentFilePath(), preg_replace(
$this->keyReplacementPattern($key),
$key . '=' . $val,
file_get_contents($this->laravel->environmentFilePath())
));
}
/**
* @param string $key
* @return string
*/
protected function keyReplacementPattern(string $key): string
{
$escaped = preg_quote('=' . env($key), '/');
return "/^" . $key . "{$escaped}/m";
}