本教程是非常經典的PHP同步修改配置文件示例教程,非常適合新手朋友學習。
主要學習了file_get_contents函數的讀寫方法,
file_get_contents函數讀取文件的方法,示例:$info=file_get_contents("文件路徑");
file_put_contents函數寫入內容的方法,示例:file_put_contents("文件路徑",寫入內容變量);
文件結構:
index.php 主頁,顯示和表單提交
config 配置文件,儲存數據
doUpdate.php 修改處理
index.php代碼:
<html>
<head>
<title>修改配置</title>
<meta charset='utf-8' />
</head>
<body>
<form action='doUpdate.php' method='post'>
<table border='' width=''>
<?php
//讀取文件
$info=file_get_contents("config.php");
//var_dump($info);
//正則
preg_match_all('/define\(\"(.*?)\",\"(.*?)\"\)/',$info,$arr);
//var_dump($arr);
//遍歷
foreach($arr[] as $k=>$v){
echo "<tr>";
echo "<td>{$v}</td>";
echo "<td><input type='text' name='{$v}' value='{$arr[2][$k]}' /></td>";
echo "</tr>";
}
?>
<tr>
<td colspan='' align='center' >
<input type='submit' value='保存' />
<input type='reset' />
</td>
</tr>
</table>
</form>
</body>
</html>config.php代碼:
<?php
define("HOST","localhost3311");
define("USER","root3311");
define("PWD","");
define("DBNAME","test3311");
?>doUpdate.php代碼:
<?php
//讀文件
$info=file_get_contents("config.php");
//var_dump($_POST);
//die;
//遍歷$_POST
foreach($_POST as $k=>$v){
//正則替換
$info=preg_replace("/define\(\"{$k}\",\".*?\"\)/","define(\"{$k}\",\"{$v}\")",$info);
}
//回填
file_put_contents("config.php",$info);
echo "ok";
header("refresh:1;url=index.php");
?>以上案列用到了正則匹配的方法修改指定內容,不會正則的可以使用<<<EOF 和 EOF的方法直接修改整個文件的內容。
$newdata = <<<php <?php 'www' = 'zztuku.com'; 'm' = 'zztuku.com'; php;






