更新数据库配置, (事例基于t p5.0)
//更新数据库配置
public function update_dbconfig()
{
$dbConfig = [
\'type\' => \'mysql\',
\'hostname\' => \'localhost\',
\'database\' => \'laofan\',
\'username\' => \'root\',
\'password\' => \'root\',
\'hostport\' => \'3306\',
];
try {
//读取系统配置内容
$dbconfig_path = APP_PATH . \'database.php\';
$site_conf = htmlentities(file_get_contents($dbconfig_path));
//替换配置项
foreach ($dbConfig as $key => $value) {
$pats = \'/\\'\' . $key . \'\\'(.*?)\\',/\';
$reps = "\'". $key. "\'". " => " . "\'".$value ."\',";
$site_conf = preg_replace($pats, $reps, $site_conf); // 正则查找然后替换
}
if (!file_exists($dbconfig_path)) {
mkdir($dbconfig_path, 0777, true);
}
$result = file_put_contents($dbconfig_path, stripslashes(htmlspecialchars_decode($site_conf)));
} catch (\Exception $e) {
return json([\'staus\'=>\'1\',\'message\'=>\'配置文件更新失败\']);
}
return json([\'staus\'=>\'2\',\'message\'=>\'配置文件更新完成\']);
}
亲测可用!