php - 更改保存到 file.php 的变量值

标签 php file

我有一个名为 variables.php 的文件

<?php
   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = 'password';
   $dbname = 'database_name';
?>

我知道我可以使用 include 访问这些变量,然后像使用任何其他变量一样使用它们,但我想知道如何更改这些变量值。我不是说 $dbhost = "other_value";。我的意思是如何将新值保存到该文件。我正在阅读有关 php 和文件打开/写入/关闭的信息,但我无法找到一种方法,如何放置自己并替换我想要的值。

我拥有的唯一信息是变量的名称,以及现在保存到它的值。我不确定我能在哪一行找到那个变量——如果它改变了什么。所以问题是,如何将(使用 php)变量 dbhost 更改为该用户将输入的任何其他内容。 (表单部分不是问题,假设用户值已保存到 $_POST['uservalue'])

提前致谢。

最佳答案

注意 添加于 04/2013:

这是个坏主意。您不应该像这样修改配置文件。如果您有可以由用户管理的配置,您应该将其存储在数据库中,或者在最坏的情况下,以通用文件格式(ini、XML 等)存储。存储数据库连接详细信息的配置文件不应由应用程序修改,而只能由管理员手动修改 - 因为文件的安全很重要,而且这种事件应该非常罕见。

在动态修改的文件上调用include/require 是自找麻烦。


下面是原答案

function change_config_file_settings ($filePath, $newSettings) {

    // Get a list of the variables in the scope before including the file
    $old = get_defined_vars();

    // Include the config file and get it's values
    include($filePath);

    // Get a list of the variables in the scope after including the file
    $new = get_defined_vars();

    // Find the difference - after this, $fileSettings contains only the variables
    // declared in the file
    $fileSettings = array_diff($new, $old);

    // Update $fileSettings with any new values
    $fileSettings = array_merge($fileSettings, $newSettings);

    // Build the new file as a string
    $newFileStr = "<?php\n\n";
    foreach ($fileSettings as $name => $val) {
        // Using var_export() allows you to set complex values such as arrays and also
        // ensures types will be correct
        $newFileStr .= "\${$name} = " . var_export($val, true) . ";\n";
    }
    // Closing ?> tag intentionally omitted, you can add one if you want

    // Write it back to the file
    file_put_contents($filePath, $newFileStr);

}

// Example usage:
// This will update $dbuser and $dbpass but leave everything else untouched

$newSettings = array(
    'dbuser' => 'someuser',
    'dbpass' => 'newpass',
);
change_config_file_settings('variables.php', $newSettings);

关于php - 更改保存到 file.php 的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9533319/

相关文章:

php - 如何防止将我的网页嵌入到 iframe 中?

Python - 如何获取文本文件中的行数

c++ - 将 QList<int> 写入文件

python - 使用生成器 ( python ) 解析 fasta 文件

检查 csv 文件中的前六个字符以获取特定序列

php ftp 函数响应消息

javascript - 如何将字符串转换为 HTML 字符串?

php - PDO 选择倍数 count()

python - python 按日期重命名文件夹中的文件

php - 英雄的 Laravel CSS 背景图像