Home > Backend Development > PHP Tutorial > php如何修改配置文件

php如何修改配置文件

WBOY
Release: 2016-06-23 14:04:00
Original
1381 people have browsed it

Config.php代码如下:

 <?phpreturn array(        'version' => '20120823',	'secretKey' => '92fe5927095eaac53cd1aa3408da8135',	'areaname' => 'China',);
Copy after login


现在想写个Common.php定义setConfig($fileName, $value)方法,去修改areaname的值。其中$fileName为Config.php文件名称, $value为更换的值,不知道具体怎么写??


回复讨论(解决方案)

file_get_contents()
file_put_contents()

function setConfig($fileName, $value) {  ob_start();  $a = @include($fileName);  ob_end_clean();  if(! is_array($a)) trigger_error("Invalid data file", E_USER_ERROR);  $a['areaname'] = $value;  file_put_contents($fileName, '<?php return ' . var_export($a, 1) . ';');}setConfig('config.php', 'aaa');
Copy after login

但是由于你的方案的限制,这个函数有着不通用的毛病
比如要想修改 secretKey 就不可以了
建议改写做
function setConfig($key, $value, $fileName='config.php') {  ob_start();  $a = @include($fileName);  ob_end_clean();  if(! is_array($a)) trigger_error("Invalid data file", E_USER_ERROR);  $a[$key] = $value;  file_put_contents($fileName, '<?php return ' . var_export($a, 1) . ';');}setConfig('areaname', 'bbb');
Copy after login

楼上正解,好的开发者一定在通用性上有想法

Related labels:
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