I have this function:
function update_config($config)
{
$buffer = array();
$buffer[] = '<?php';
foreach( $config as $key => $value ) {
$buffer[] = '$config[\'' .$key. '\'] = \'' .str_replace('\'', ''', $value). '\';';
}
$buffer[] = '?>';
$data = implode("\n", $buffer);
$path = $_SERVER['DOCUMENT_ROOT'] . 'settings.php';
$fp = fopen($path, 'wb');
if ($fp) {
flock($fp, LOCK_EX);
$len = strlen($data);
fwrite($fp, $data, $len);
flock($fp, LOCK_UN);
fclose($fp);
}
}
is working very well, it insert like this $config[title] = 'Demo title';
How I can make to don't overwrite all file when I change something? Exemple, if I have 3 entries in settings.php and when I want to insert another, file is totaly rewrited with new insert only!
And I want when some exist like $config[title] change only value!
Thank you!
CodePudding user response:
better way is to save your config as a json file. then you can read all content into an array, change some variables and write the new one to the file.
{
"title": "hello",
"name": "test",
"bla": "muh"
}
<?php
$string = file_get_contents('config.json');
$config = json_decode($string, TRUE);
$config['title'] = "new title";
$string = json_encode($config);
file_put_contents('config.json', $string);
?>
Edit:
same can you do with your $config array in php language:
include 'config.php'; // load all $config vars
$config['title'] = "new title";
// now write $config vars to file
CodePudding user response:
With a little extra additions, var_export()
will help you do what you're looking to. It accepts any PHP variable and will export it to a parsable representation.
Generally you would want to load the full config array, modify only desired values, and re-write the full array back to file.
You can do so like this:
$config = [
"myValue1" => 10,
"myValue2" => "Hello, world"
];
$configCode = '<?php $config = ' . var_export($config, true) . ';';
file_put_contents("config.inc.php", $configCode);