首页 > 解决方案 > 在php中更改文件中的变量值

问题描述

我有一个文件,它是一个小place_config.php文件。

以此为例,我正在设置我的变量

<?php

//config file
$place_config = array(
    'credentials' => array(
        'sid' => 'some_value',
        'token' => 'some_token'
    )
?>

为了方便起见,我想从用户的管理面板更改sidand 。token我怎样才能有效地做到这一点。我理解的一种解决方案是将文件的内容放在一个字符串中,并$_REQUEST在发布请求之后将整个字符串写入文件?这是一种有效的方法吗?

标签: php

解决方案


提交带有正确输入的表单,并在提交时调用update_place_config()

function update_place_config() {
    include('place_config.php');
    $place_config['credentials']['sid'] = $_POST['sid'];
    $place_config['credentials']['token'] = $_POST['token'];
    $output = '<?php $place_config = ' . var_export($place_config, true) . '; ?>';
    file_put_contents('place_config.php', $output);
    return $place_config; //if you want to get the new config
}

另外一个选项:

$content = file_get_contents('place_config.php');
$content = preg_replace("/('sid' =>) '[^']+'/", "$1 '{$_POST['sid']}'", $content);
file_put_contents('place_config.php', $content);

如果它需要是一个文件,我个人会存储在数据库中或使用 JSON。


推荐阅读