tags:

views:

61

answers:

3

Hello,

Am developing an admin center where I can edit configuration files (written in PHP). I do NOT want to store these values in a mySQL table (for various reasons). So say my config.php has contents like:

   <?php
     $option1 = 1;
     $option2 = 2;
     $option4 = 5;
     $option7 = array('test','a','b',c');
   ?>

Now say in one of the admin pages I will only be changing a few values like option2 or option4 etc. Any ideas on what would be the best way to go about this.

I know one option is to read the PHP file completely and write parts of it using REGEX. Any way to make this more efficent? I don't want the config.php file to break because of some error on the user's end. Any ideas on how to ensure that it works?

+2  A: 

If you have some liberty about the way you store configuration values, you may use ini files.

All you have to do is load the content of the ini file in an array with parse_ini_file, then modify values in that array and finally overwrite the file with new values, as described in this comment.

For obvious security reasons it's a good idea to place those files out of your document root.

sample content of ini file :

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"

sample code (using safefilewrite function) :

<?php
$ini_file = '/path/to/file.ini';
$ini_array = parse_ini_file($ini_file);

$ini_array['animal'] = 'CAT';

safefilerewrite($file, implode("\r\n", $ini_array));
?>
Benjamin Delichère
+1 For basic configuration data, INI files or XML files (or JSON encoded data) should indeed suffice. Though you could also create a dynamic PHP file (which always is overwritten) containing the configuration data if you think parsing the INI/XML/JSON is too much overhead. Lots of options, all will work :p.
wimvds
+1  A: 

var_export() is probably the function you're looking for.

Col. Shrapnel
A: 

You can write/read the settings to a file using the following code:

$content = array();
//fill your array with settings;
$fh = fopen ( $bashfile, 'w' ) or die ( "can't open file" );
fwrite ( $fh, $content );
fclose ( $fh );

to read it you use: file_get_contents() //this will return a string value OR Line by line:

$lines = file('file.txt');
//loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
print "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
Robijntje007