views:

189

answers:

4

Hello everybody! 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.

+6  A: 

It is advisable to use a structured file format of some sort for this purpose.
Consider using CSV, Ini, XML 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);
Gordon
How to check (from php) if the included file does not contain syntax errors?
SaltLake
@SaltLake it cannot contain errors if you solely use it through the class above. It's just an exported parseable array. However, you can check whether a file contains valid PHP syntax with [`runkit_lint_file`](http://de2.php.net/manual/en/function.runkit-lint-file.php) but runkit is a PECL extension and generally not recommended in production code.
Gordon
A: 

Have a look at the examples for str_replace ( http://us3.php.net/manual/en/function.str-replace.php )

Dominik
+1  A: 

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);
pedro
Is there a specific point in writing the exact same contents back to the file again?
fireeyedboy
+1  A: 

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";
}
MetaCipher