Page 1 of 1
Change variable values in config file
Posted: Sun May 06, 2007 1:22 am
by arukomp
Hello,
Let's say I have a config.php file with following contents:
Code: Select all
<?php
$dbhost = "localhost";
$dbuser = "db_user";
$dbpass = "db_pass";
$dbname = "db_name";
?>
Now I need a script to be able to change only one variable's value without touching the others. For example, a user comes to Administration area, clicks on "MySQL settings" and then changes MySQL login details ($dbuser and $dbpass only). So how do I write the new values into config.php file without touching the others.
Thanks for any suggestions
Posted: Sun May 06, 2007 5:43 am
by kaszu
Read the values from the config file and then write all values into the file.
Code: Select all
$new_db_host = 'localhost';
$new_db_user = 'db_user';
$new_db_pass = 'db_pass';
$new_db_name = 'db_name';
$content = '<'."?php\n\n".
'$dbhost = "'.$new_db_host."\";\n".
'$dbuser = "'.$new_db_user."\";\n".
'$dbpass = "'.$new_db_pass."\";\n".
'$dbname = "'.$new_db_name."\";\n\n?".'>';
$h = fopen('PATH/TO/CONFIG/FILE/config.php', 'w');
if ($h)
{
write( $h, $content );
fclose( $h );
}
Posted: Sun May 06, 2007 1:12 pm
by arukomp
Thanks for that

It works
Posted: Sun May 06, 2007 5:06 pm
by John Cartwright
Be very, very careful about injecting dynamic php into files. There is a reason we use configuration files, such as xml, plaintext, ini, etc

Posted: Mon May 07, 2007 3:11 am
by arukomp
So what do you want to say? I shouldn't use php config files? If so, then how do I store settings and access them other way?
Posted: Mon May 07, 2007 3:41 am
by CoderGoblin
parse_ini_file would be my method. You can read/write the used config file as a normal file. Any PHP code inserted will not "run".
Posted: Mon May 07, 2007 4:29 am
by arukomp
Thanks, but won't people be able to see ini file's contents if they open it through browser or download it (through browser)? Is it really secure?
Posted: Mon May 07, 2007 5:34 am
by stereofrog
You can place it outside of web-root or make it php-parsed and prepend with something like ;<? die(); ?>
However, in a trusted environment, php config file is still the best option, see
http://de.php.net/var_export for the examples of proper usage).