Reading and Writing Configuration Files
I'm writing a small script which generates some configuration for devices. I want to have separate file, where I'm storing configuration, and change some strings during printing the content of the configuration to the browser. How can I replace string in a line of the file with a variable from $_POST['somevariable']?
-- Additional info --
I have several types of devices. I want to have separate file with configuration template for each type of device. If someone want to change configuration of some type device they will change that file not php file. But in order to use this template in php I have to replace some string in that file before printing out to web page, e.g.: sys info hostname %host_name% sys info location %location% ip set %ip% the strings inbetween %% (could be any other) characters should be replaced with $_POST["host_name"], $_POST["location"], $_POST["ip"] etc. All these params gotten from the posted form.
It is advisable to use a structured file format of some sort for this purpose.
Consider using CSV, Ini, XML, JSON or YAML and use appropriate APIs to read and write them.
Another alternative would be to store the configuration in an array and then either use serialize/unserialize or use var_export/include to use it.
Very basic example:
class MyConfig
{
public static function read($filename)
{
$config = include $filename;
return $config;
}
public static function write($filename, array $config)
{
$config = var_export($config, true);
file_put_contents($filename, "<?php return $config ;");
}
}
You could use the class like this:
MyConfig::write('conf1.txt', array( 'setting_1' => 'foo' ));
$config = MyConfig::read('conf1.txt');
$config['setting_1'] = 'bar';
$config['setting_2'] = 'baz';
MyConfig::write('conf1.txt', $config);
Use SQLite. You can then query for specific data, and still have a local file. FYI - PDO quote automatically adds single quotes around a value.
$Filename = "MyDB.db";
try {
$SQLHandle = new PDO("sqlite:".$Filename);
}
catch(PDOException $e) {
echo $e->getMessage()." :: ".$Filename;
}
$SQLHandle->exec("CREATE TABLE IF NOT EXISTS MyTable (ID INTEGER PRIMARY KEY, MyColumn TEXT)");
$SQLHandle->beginTransaction();
$SQLHandle->exec("INSERT INTO MyTable (MyColumn) VALUES (".$SQLHandle->quote("MyValue").")");
$SQLHandle->exec("INSERT INTO MyTable (MyColumn) VALUES (".$SQLHandle->quote("MyValue 2").")");
$SQLHandle->commit();
$Iterator = $SQLHandle->query("SELECT * FROM MyTable ORDER BY MyColumn ASC");
unset($SQLHandle);
foreach($Iterator as $Row) {
echo $Row["MyColumn"]."\n";
}
I agree with Gordon.
If you don't follow his advice you can do something like this:
$file = file_get_contents('./conf.tpl');
$file = str_replace('%server%', 'localhost', $file);
file_put_contents('./conf.txt', $file);