您现在的位置是:首页 > 其他

李清波 2014-06-01 其他 53851 复制当前网址

PHP设置配置文件的方法

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 为文件的完整路径,也就是绝对路径。

通过file_get_contents文件获取配置文件的所有信息

再通过preg_replace方法把我们所修改,也是所提交过来的配置信息进行与原先的配置信息替换。

在通过file_put_contents把修改的所有信息替换了。


上面的方法不仅仅可以用在修改配置信息,还可以使用到修改任何文件

如果转载,请注明文章来源于李清波博客

文章来源:http://liqingbo.com/blog-237.html

评论