php - 在php中更改文件中的变量值
问题描述
我有一个文件,它是一个小place_config.php
文件。
以此为例,我正在设置我的变量
<?php
//config file
$place_config = array(
'credentials' => array(
'sid' => 'some_value',
'token' => 'some_token'
)
?>
为了方便起见,我想从用户的管理面板更改sid
and 。token
我怎样才能有效地做到这一点。我理解的一种解决方案是将文件的内容放在一个字符串中,并$_REQUEST
在发布请求之后将整个字符串写入文件?这是一种有效的方法吗?
解决方案
提交带有正确输入的表单,并在提交时调用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。
推荐阅读
- mdx - MDX - 显示此 MDX 查询的维度标签/值
- css - Bootstrap(在 Laravel 上) - 标题下拉列表在一页上变得透明
- c - 将 elf32_Word 打印为单词
- java - secLdap 插件发生内部错误。无效的
- angular - 带有管道的 ngFor 标签重复多少次
- vue.js - 使用 Axios 调用后 Cookie 未存储在浏览器中
- javascript - Javascript 和 html:在文档之前更新窗口
- php - 计算在 Laravel 中不起作用的登录数
- arrays - 如何在逻辑应用程序中循环遍历数组?
- python - Pandas:根据优先级创建具有列值的列