8

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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 2
    Welcome to stackoverflow. Your question is pretty broad. Can you give us some more information about what exactly you need to replace? Do you need to replace a specific line (line 10 for instance)? Or do you need to replace some placeholder? Can you give an example extract of how the content of the file looks, and what part need to be replaced by what? – Decent Dabbler Feb 10 '10 at 14:11
  • In light of your additional information, I'd say that pedro's answer would work very well. Remember that the first two parameters for str_replace() can be arrays. (In any event, be sure to sanitize the $_POST elements.) – GZipp Feb 11 '10 at 14:13

3 Answers3

29

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);
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • How to check (from php) if the included file does not contain syntax errors? – foreline Oct 22 '10 at 12:22
  • @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 Oct 22 '10 at 12:27
  • You might as well serialize / unserialize an array and be done with it. – MetaCipher Jul 27 '11 at 20:34
  • @Meta yeah, I mentioned serializing as well (see above). The main benefit of using var_export is that the result is still php and is easy to edit with regular text editors. Serialized arrays are less convenient to edit. – Gordon Jul 27 '11 at 21:14
  • 1
    @MetaCipher that would be another option but really, why serialize it to some other format at all? For a simple solution (and that's what the example above is), using plain old arrays is fine and fast. – Gordon Jul 29 '11 at 12:10
  • Can I use PHP files for the config file or can I only use ini, csv, xml or yaml? – LightningBoltϟ Dec 17 '13 at 07:52
  • @Me123 whatever suits your needs. The above example code is actually writing an executable PHP array into a text file. – Gordon Dec 17 '13 at 14:55
5

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
  • 274
  • 2
  • 8
3

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
  • 411
  • 3
  • 9