php自定义配置文件简单写法

php MVC 要在controller或者model中引入自定义配置文件
1 配置文件编写
config.ini
内容如下:

#配置host
$host=”10.12.100.10”;

#配置管理员
$Admin=”xiaoli,sunny”;

2 获取配置项(opeconfig.php)

function updateconfig($name,$val) //更新配置项
{
  $str=file_get_contents("配置文件的路径");  //我是用的是绝对路径,相对路径有点略坑
  $str2 = preg_replace("/" . $name . "=(.*);/", $name . "=\"" . $val . "\";",$str);
  file_put_contents("配置文件的路径", $str2);
}
function getconfig($name) //获取配置项
 {
  $str=file_get_contents("配置文件的路径");
  $config = preg_match("/" . $name . "=\"(.*)\";/", $str, $res);
  return  $res[1];
 }

3 在controller中引入opeconfig.php(我引入的是绝对路径,php太坑,相对路径很容易出错)
require_once(“opeconfig.php”)
在controller类中使用时,比如想要得到管理员($Admin)的值,直接如下调用即可
getconfig(“Admin”);
更新该值时,调用
updateconfig(“Admin”,“wangwu,lisi”)//配置文件中相应值将更新

猜你喜欢

转载自blog.csdn.net/sunny__2018/article/details/82223355