php设置配置文件的方法
变量 $config 是我们所提交过来的配置信息,是以数组形式存储的。
function set_config($config){
if(!is_array($config)) return FALSE;
$configfile = CONF_PATH.'config.php';
if(!is_writable($configfile)) return('Please chmod ./config.inc.php to 0777 !');
$pattern = $replacement = array();
$str = file_get_contents($configfile);
foreach($config as $k=>$v){
$pattern[$k] = "/['\"]".strtoupper($k)."['\"]\s*=>\s*([']?)[^']*([']?)/is";
$replacement[$k] = "'".strtoupper($k)."'=> \${1}".$v."\${2}";
}
$str = preg_replace($pattern, $replacement, $str);
return file_put_contents($configfile, $str);
}
上面的$configfile 为文件的完整路径,也就是绝对路径。
立即学习“PHP免费学习笔记(深入)”;
通过file_get_contents文件获取配置文件的所有信息
再通过preg_replace方法把我们所修改,也是所提交过来的配置信息进行与原先的配置信息替换。
在通过file_put_contents把修改的所有信息替换了。
上面的方法不仅仅可以用在修改配置信息,还可以使用到修改任何文件
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号