Suppose I have a database configuration form like the following image:
In CodeIgniter, the user needs to edit the files at ...\\application\\config\\database.php
and change the hostname, username, password and other required info.
Now I want to do the task automatically when a user fills out the above form and clicks the "Save" button. I guess I need to perform some file write operation using PHP, but I don't know how to find and replace specific portions of a file.
How can I change hostname, username, password, and database name based on the form input in the CodeIgniter database configuration file?
$db_info = $this->input->post(['hostname', 'username', 'password', 'database']);
You'll have to validate the information provided by the user before actually trying to save anything.
for example; You might try to run mysqli_connect on the provided settings to manually connect like this:
if ( @mysqli_connect($db_info['hostname'], $db_info['username'], $db_info['password'], $db_info['database']) ) {
then you'll have to write these data into the file, which is pretty simple in CodeIgniter.
You'll have to take a copy of database.php & put it somewhere in your installation folder replacing <?php
with something like this <?php echo '<?php' . "\\n"; ?>
<?php echo '<?php' . "\\n"; ?>
Then you go ahead and replace $db['default'] = array
entries adding your custome variables like this
$db['default'] = array(
'dsn' => '',
'hostname' => '<?php echo $hostname; ?>',
'username' => '<?php echo $username; ?>',
'password' => '<?php echo $password; ?>',
'database' => '<?php echo $database; ?>',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
After that it's as easy as loading the view in your controller & caching it to a variable for example
$DBConfig = $this->load->view('install/config/database', $db_info, TRUE);
Then writing the output to the desired path as follows:
$this->load->helper('file');
write_file(APPPATH.'config/database.php', $DBConfig);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.