Home > Backend Development > PHP Tutorial > How to set up configuration files in PHP

How to set up configuration files in PHP

高洛峰
Release: 2016-10-21 11:09:15
Original
1548 people have browsed it

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);
    }
Copy after login

   


上面的$configfile 为文件的完整路径,也就是绝对路径。

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

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

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


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


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template