将变量值更改保存到file.php

Ked*_*dor 3 php file

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

<?php
   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = 'password';
   $dbname = 'database_name';
?>
Run Code Online (Sandbox Code Playgroud)

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

我唯一的信息是变量的名称,以及现在保存的值.我不确定在哪一行我能找到变量 - 如果这改变了什么.所以问题是,如何将(使用php)变量更改dbhost为其他任何东西,用户将放入表单.(表单部分不是问题,假设用户值已保存到$_POST['uservalue'])

提前致谢.

Dav*_*dom 8

注释已添加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);
Run Code Online (Sandbox Code Playgroud)