Tuesday, March 10, 2015

Update An Existing Configuration File In PHP

In PHP, it's a widely used practice to set a site's configuration details by defining constants in a separate "config" file.

This config file mostly contains important data such as security keys, database connections, paths, debug and logging information, and many more.

Normally, the config file contents are manually set by hand. However, we can also update or add contents from another new config file into an existing config file, which is being demonstrated in the following script. This script will update an existing defined constant with the new value, or add the constant if it doesn't exist. (Please change the FOO_CONFIG and NEW_FOO_CONFIG constants on top to your file path):


// Define the foo config file paths.
define('FOO_CONFIG',     __DIR__ . '/foo-config.php');          // The existing foo config file.
define('NEW_FOO_CONFIG', __DIR__ . '/new-foo-config.php');      // The new foo config file.
// ==


* Updates NEW_FOO_CONFIG contents into existing FOO_CONFIG file.
function updateFooConfig()
        $fooConfig        = file_get_contents(FOO_CONFIG);              // Read from existing FOO_CONFIG contents into string.
        $newFooConfig     = file_get_contents(NEW_FOO_CONFIG);          // Read from the NEW_FOO_CONFIG contents into string.
        $newFooConfigLine = strtok($newFooConfig, "\r\n");              // Read each line in the NEW_FOO_CONFIG string.
        while ($newFooConfigLine !== false)
            // Note: Patterns must be enclosed with delimiters, e.g. "/".
            if (preg_match("/\s*define\s*\(\s*('.*?')\s*,\s*('*.*?'*)\s*\)\s*;\s*/", $newFooConfigLine, $matches))              // If the NEW_FOO_CONFIG line is a define(...).
                if (preg_match("/\s*define\s*\(\s*" . $matches[1] . "\s*,\s*('*.*?'*)\s*\)\s*;\s*/", $fooConfig, $matches2))    // If FOO_CONFIG string contains the same define(...) constant.
                    $fooConfig = str_replace(trim($matches2[0]), trim($matches[0]), $fooConfig);                                // Replace FOO_CONFIG string with this NEW_FOO_CONFIG line string.
                    $fooConfig = $fooConfig . PHP_EOL . $newFooConfigLine;                                                      // Append this NEW_FOO_CONFIG line to FOO_CONFIG string if not found.

            $newFooConfigLine = strtok( "\r\n" );                       // Read next line in NEW_FOO_CONFIG string.
        if (file_put_contents(FOO_CONFIG, $fooConfig) === false)        // Wrtie the FOO_CONFIG string back to it's file, overwrite existing.
            throw new Exception("Foo config file '" . FOO_CONFIG . "' cannot be written.");
    catch(Exception $e)
        // TODO: Throw or log the exception.

If you find this post helpful, would you buy me a coffee?

No comments:

Post a Comment