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

 1090

本教程是非常经典的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;


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

评论(0)条

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

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

    编辑推荐