How to do this trick in reading php files and modify it's contents?

hello ,

i have simple php file similar to this style


<?php

// driver of database
$config['driver'] = 'mysql';

// database name
$config['database'] = 'a';

// database username
$config['username'] = 'user';

// database user password
$config['password'] = '123'

?>

so i wrote a function to modify values of any one of this variables


function modify($key,$value)
{
	require('config.php');
	$config[$key] = $value;				
	$handler	=	fopen('config.php','w');
	$contents = "<?php";
								foreach($config AS $a=>$b)
										{
											$contents .= '$config[\\''.$a.'\\']			=			\\''.$b."';\
";
										}
										
									$contents .= "\
?>";
									fwrite($handler,$contents);
									fclose($handler);
}

and it’s work good … but my problem that i want when i use this function and it’s rewrite the config file … and want it to write the file with it’s first style (with // comments ) … because my current method will rewrite the config file and it will be like this (without // comments) :


<?php

$config['driver'] = 'mysql';

$config['database'] = 'a';

$config['username'] = 'user';

$config['password'] = '123'

?>

so is there any other method to solve my problem :slight_smile: ?

Hi there.
The problem you’re having here is based on the loading of the php file as an included script and recreating its variables in text form from scratch.

What you’re looking for is a means of editing the file, not recreating it.

I’ve rewritten the function to act as you’ve described.

function modify($key,$value)
{
    //Get the original contents of the file in a text string
    $contents = file_get_contents('config.php');
    
    //Open the file for writing (The file truncates to 0 at this point.)
    $handler  = fopen('config.php','w');
    
    //Regex pattern to match the line of the key passed to the function.
    $pattern = '/\\$config\\[\\''.$key.'\\'] = .+/';
    $replace = '$config[\\''.$key.'\\'] = \\''. $value .'\\';';
    
    //Modify the text, which should only be one line. Leave the rest in tact.
    $contents = preg_replace($pattern, $replace, $contents);
    
    //Write the modified contents back to the file and close.
    fwrite($handler,$contents);
    fclose($handler);
}

I hope this helps!