PHP同步修改配置文件示例教程+源码

 2406

本教程是非常经典的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. <html>
  2.    <head>
  3.        <title>修改配置</title>
  4.        <meta charset='utf-8' />
  5.    </head>
  6.   
  7.    <body>
  8.        <form action='doUpdate.php' method='post'>
  9.            <table border='' width=''>
  10.                <?php
  11.                    //读取文件
  12.                    $info=file_get_contents("config.php");
  13.                    //var_dump($info);
  14.   
  15.                    //正则
  16.                    preg_match_all('/define\(\"(.*?)\",\"(.*?)\"\)/',$info,$arr);
  17.                    //var_dump($arr);
  18.   
  19.                    //遍历
  20.                    foreach($arr[] as $k=>$v){
  21.                        echo "<tr>";
  22.                            echo "<td>{$v}</td>";
  23.                            echo "<td><input type='text' name='{$v}' value='{$arr[2][$k]}' /></td>";
  24.                        echo "</tr>";
  25.                    }
  26.                ?>
  27.                <tr>
  28.                    <td colspan='' align='center' >
  29.                        <input type='submit' value='保存' />
  30.                        <input type='reset'  />
  31.                    </td>
  32.                </tr>
  33.            </table>
  34.        </form>
  35.    </body>
  36. </html>

config.php代码:

  1. <?php
  2.    define("HOST","localhost3311");
  3.    define("USER","root3311");
  4.    define("PWD","");
  5.    define("DBNAME","test3311");
  6. ?>

doUpdate.php代码:

  1. <?php
  2.    //读文件
  3.    $info=file_get_contents("config.php");
  4.   
  5.    //var_dump($_POST);
  6.    //die;
  7.    //遍历$_POST
  8.    foreach($_POST as $k=>$v){
  9.        //正则替换
  10.        $info=preg_replace("/define\(\"{$k}\",\".*?\"\)/","define(\"{$k}\",\"{$v}\")",$info);
  11.    }
  12.   
  13.    //回填
  14.    file_put_contents("config.php",$info);
  15.    echo "ok";
  16.    header("refresh:1;url=index.php");
  17.   
  18. ?>

以上案列用到了正则匹配的方法修改指定内容,不会正则的可以使用<<<EOF 和 EOF的方法直接修改整个文件的内容。

  1. $newdata = <<<php
  2. <?php
  3. 'www' = 'zztuku.com';
  4. 'm' = 'zztuku.com';
  5. php;


TAG标签:
本文网址:https://www.zztuku.com/detail-12948.html
站长图库 - PHP同步修改配置文件示例教程+源码
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐