pelachile
pelachile

Reputation: 587

Codeigniter dynamic configuration

How do I let users set the database configuration for a new CI install?

My intention is to have a form that allows them to enter the data then either generate a new config file or to set the options in the database.php file.

Is this possible?

Upvotes: 3

Views: 2161

Answers (1)

No Results Found
No Results Found

Reputation: 102745

Let's say you want to create a database config file. Here's how I do it:

Create a "dummy" config file by copying a real one, and use values that look something like this:

$db['default']['hostname'] = '__HOSTNAME__';
$db['default']['username'] = '__USERNAME__';
$db['default']['password'] = '__PASSWORD__';
$db['default']['database'] = '__DATABASE__';

Have the user complete the installation form, and verify all the data by testing a database connection. Next, use file_get_contents() to grab the content of the "dummy" config file, use a simple str_replace() to rewrite the values with the ones the user provided, then write the new content to your real config file overwriting the entire thing.

Here's part of the actual code I'm using for creating the file, just to get an idea. Bear in mind that I'm running this on a totally separate CI installation (the "installer"), and this is not a copy/paste example:

// Write the database configuration file
$config = array(
    'hostname',
    'username',
    'password',
    'database',
);

$data = file_get_contents(APPPATH.'config/dummy_database.php');
$file = '../private/config/database.php';

// Oops! Just caught this after posting: str_replace() accepts arrays.
// TODO: Use the array method instead of a loop!
foreach ($config as $item)
{
    $data = str_replace('____'.strtoupper($item).'____', mysql_escape_string($this->data[$item]), $data);
}
if (write_file($file, $data))
{
    $this->message('Database configuration file was written!', 'success');
    @chmod($file, 0644);
    {
        if (is_really_writable($file))
        {
            $this->message('The database configuration is still writable, make sure to set permissions to <code>0644</code>!', 'notice');
        }
    }
}
else
{
    $this->message('Could not write the database configuration file!');
    redirect('step_4');
}

This retains the original copy of the "dummy" config file. You could use the same logic for editing, just read the current config values for anything the user has not changed and do the same string replacement technique.

Upvotes: 2

Related Questions