Reading and Writing Configuration Files

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);

Leave a Comment