PHP同步修改配置文件示例教程+源码
本教程是非常经典的PHP同步修改配置文件示例教程,非常适合新手朋友学习。
主要学习了file_get_contents函数的读写方法,
file_get_contents函数读取文件的方法,示例:$info=file_get_contents(“文件路径”);
file_put_contents函数写入内容的方法,示例:file_put_contents(“文件路径”,写入内容变量);
文件结构:
index.php 主页,显示和表单提交
config 配置文件,储存数据
doUpdate.php 修改处理
index.php代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<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代码:
1
2
3
4
5
6
|
<?php define( "HOST" , "localhost3311" ); define( "USER" , "root3311" ); define( "PWD" , "" ); define( "DBNAME" , "test3311" ); ?> |
doUpdate.php代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?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的方法直接修改整个文件的内容。
1
2
3
4
5
|
$newdata = <<<php <?php 'www' = '11px.cn' ; 'm' = '11px.cn' ; php; |