Home  >  Article  >  Backend Development  >  How to modify local files in php

How to modify local files in php

藏色散人
藏色散人Original
2020-08-13 09:07:282525browse

How to modify local files in php: first use the fopen function to open the local file that needs to be modified; then modify the file content through the "fwrite($fp,$password);" method; finally use the "fclose" function to close and Just save the file.

How to modify local files in php

Recommended: "PHP Video Tutorial"

php reads and modifies txt files

//txt文件中只有一行数据 读
$fp = fopen("password.txt", "r");
if($fp)
{
     $pwd = fgets($fp);
}
else
{
     echo "打开文件失败";
}
fclose($fp);

View Code

//txt文件中只有一行数据 写
 1 $fp = fopen("password.txt", "w");//文件被清空后再写入
 2 if($fp)
 3 {
 4      $flag=fwrite($fp,$password);
 5      if(!$flag)
 6      {
 7           echo "写入文件失败<br>";
 8           break;
 9      }
10 }
11 fclose($fp);
//txt文件中有多行数据  读 以数组的形式
 1 $path="wifi_customer_settings.txt";
 2 $body = file_get_contents($path);
 3 if( file_exists( $path ) )
 4 {
 5     $body = file_get_contents($path);//转为数组
 6 //echo "<script language=javascript>alert(&#39;文件存在&#39;);</script>";
 7 }
 8 else
 9 {
10    // echo "<script language=javascript>alert(&#39;文件不存在 $path&#39;);</script>";
11 }
12 $cbody = file($path);
13 //print_r($cbody);
14 $wifissid=$cbody[0];
15 $wifipwd=$cbody[1];
16 $wifissid=str_replace(&#39;wifiSSID=&#39;,&#39;&#39; ,$wifissid);//文本替换 将$wifissid值的wifiSSID替换为&#39; &#39;
17 $wifipwd=str_replace(&#39;wifiPWD=&#39;,&#39;&#39; ,$wifipwd);
//txt文件中有多行数据 写  以数组的形式
1 $path="wifi_customer_settings.txt";
2 $wifissid2=$_POST[&#39;wifissid&#39;];
3 $wifipwd2=$_POST[&#39;wifipwd&#39;];
4 $arr=array("wifiSSID=".$wifissid2,"\n","wifiPWD=".$wifipwd2);
5 $fp=fopen($path, &#39;w&#39;);
6 fputs($fp,$arr[0]); 
7 fputs($fp,$arr[1]);
8 fputs($fp,$arr[2]);
9 fclose($fp);

The above is the detailed content of How to modify local files in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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