gpt4 book ai didi

php - 如何替换codeigniter中的数据库配置?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:43:14 28 4
gpt4 key购买 nike

我为我的网站安装了一个疯狂的安装程序。但我不知道如何替换 hostnameusernamepassworddatabase。使用来自输入字段的值。这是来自 config/database.php 文件的代码。

$db['default'] = array(
'dsn' => '',
'hostname' => 'db_host',
'username' => 'db_user',
'password' => 'db_pass',
'database' => 'db_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

但是这段代码给了我那个错误。

enter image description here

以及 controller 中的这段代码。

function configure_database() {
// write database.php
$data_db = file_get_contents('./application/config/database.php');
// session_start();
$data_db = str_replace('db_name', $_POST['dbname'], $data_db);
$data_db = str_replace('db_user', $_POST['username'], $data_db);
$data_db = str_replace('db_pass', $_POST['password'], $data_db);
$data_db = str_replace('db_host', $_POST['hostname'], $data_db);
file_put_contents('./application/config/database.php', $data_db);
}

最佳答案

您可以按如下方式格式化 config/database.php :

$db['default']['username'] = "%USERNAME%";
$db['default']['password'] = "%PASSWORD%";
$db['default']['database'] = "%DATABASE%";
$db['default']['hostname'] = "%HOSTNAME%";
$db['default']['dbdriver'] = "mysqli";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";

然后用这个方法写入:

function configure_database() {
// write database.php
$data_db = file_get_contents('config/database.php');
// session_start();
$temporary = str_replace("%DATABASE%", $_POST['dbname'], $data_db);
$temporary = str_replace("%USERNAME%", $_POST['username'], $temporary);
$temporary = str_replace("%PASSWORD%", $_POST['password'], $temporary);
$temporary = str_replace("%HOSTNAME%", $_POST['hostname'], $temporary);
// Write the new database.php file
$output_path = './application/config/database.php';
$handle = fopen($output_path,'w+');
// Chmod the file, in case the user forgot
@chmod($output_path,0777);
// Verify file permissions
if(is_writable($output_path)) {
// Write the file
if(fwrite($handle,$temporary)) {
return true;
} else {
return false;
}
} else {
return false;
}
}

基本上它会检查每一行是否匹配,然后用发布的数据替换它们,最后再次将其写入数据库配置。

引用:CodeIgniter Installer

关于php - 如何替换codeigniter中的数据库配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55279633/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com