I'm trying to build a small CMS using CodeIgniter, and I need to be able to dynamically update some variables within the application/config.php
So far I did:
private function update_file ($file, $var, $var_name) {
$start_tag = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
";
if (file_exists($file)) {
require_once ($file);
$updated_array = array_merge($$var_name, $var);
$data = $start_tag."\$".$var_name." = ".var_export($updated_array, true).";";
file_put_contents($file, $data);
} else {
return false;
}
}
Everything works just fine! The result in the config.php file will be:
<?php ...;
$config = array (
'base_url' => '',
...
...
);
But what if I would like to maintain the original config.php file format with comments, spaces and
separated declared $config['key'] = 'value' ... ?
Is that possible ?
EDIT:
Thank you for your answers, very precious. I found a slightly different solution for my needs, performing a preg_replace on the return of file_get_contents() and then write back on the file the new resulting string. File maintains the exact original clean format.
private function update_file ($file, $var, $var_name) {
if (file_exists($file)) {
require_once ($file);
$contents = file_get_contents($file);
$updated_array = array_merge($$var_name, $var);
$search = array();
$replace = array();
foreach($$var_name as $key => $val) {
$pattern = '/\$'.$var_name.'\[\\\''.$key.'\\\'\]\s+=\s+[^\;]+/';
$replace_string = "\$".$var_name."['".$key."'] = ".var_export($updated_array[$key], true);
array_push($search, $pattern);
array_push($replace, $replace_string);
}
$new_contents = preg_replace($search, $replace, $contents);
write_file($file, $new_contents);
}
Maybe it requires some slight performance improvements. But this is my baseline idea.