Your Developer Exam showed me just how much there is to PHP. 您的开发人员考试表明我只是有多少是PHP的。”
罗斯

你经常有保存或读取在web开发中的资源做一个简单的方法是从文件中读取和写入。

阅读文件

我们将介绍使用file_get_contents函数读取一个文件的最简单方法。
Simply give it the relative path of the file to read / /简单地给它的文件的相对路径读取
contents = file_get_contents ( ' text . txt ' ) ; $内容= file_get_contents(“文本txt');
$ contents ; 回声 $的内容;
文件读取的text.txt文件,并输出到一个字符串。 这是最简单的方法来读取一个文件,你也可以限制你读到这样的金额
contents = file_get_contents ( ' text . txt ' , false , null , 0 , 1024 ) ;内容= file_get_contents(“文本TXT。”,FALSE,NULL,0,1024);
这读取的前1024个字节或第一千字节。 您还可以使用file_get_contents函数来读取网页所以:
Simply give it the url of the web page to read / /简单地给它读取网页的URL
contents = file_get_contents ( ' http : // www . google . com ' ) ; $内容= file_get_contents('。HTTP:/ / WWW谷歌COM“);
会读谷歌的主网页!

写入文件

写入文件的最简单方法是使用file_put_contents功能。
Simply give it the file to write to and the data / /简单地给它的文件写入数据
data = ' hi there ' ; 数据=“喜有”;
' text . txt ' , $ data ) ; file_put_contents(TXT文本数据);
如果有错误或如果它是全成,所以我们可以进一步提高,有些像逻辑代码写的字节数返回false:
Simply give it the file to write to and the data / /简单地给它的文件写入数据
data = ' hi there ' ; 数据=“喜有”;
file_put_contents ( ' text . txt ' , $ data ) ) 如果(!file_put_contents(“文本。txt'数据$))
{
" There was an error writing your data to the text . txt file " ; 回声 是一个错误数据写入TXT文本文件”。;
}
这个功能实际上是将创建一个不存在的文件,默认情况下,以及覆盖现有文件。 因此,它可能是一个好主意,只让通过设置文件的附加标志的文件追加。
Simply give it the file to write to and the data / /简单地给它的文件写入数据
data = ' hi there ' ; 数据=“喜有”;
file_put_contents ( ' text . txt ' , $ data , FILE_APPEND ) ) 如果(file_put_contents(“文本。txt' 数据,FILE_APPEND))
{
" There was an error writing your data to the text . txt file " ; 回声 是一个错误数据写入TXT文本文件”。;
}

良好做法

一般处理文件时,它很高兴地看到,如果该文件,然后用它做的东西存在,这使得你的代码更可靠。 要做到这file_exists函数可以使用。
Simply give it the file name to check that exists / /简单地给它的文件名 ​​检查存在
file_exists ( ' text . txt ' ) ) 如果(file_exists(“文本。txt' ))
{
" Your file doesn ' t exist ! " ; 呼应 您的文件存在!”;
返回;
}
/ *
Rest of the file accessing code . *其他文件的存取代码
* /

已提供任何意见。
安全形象
书面由多米尼克·斯金纳
最后更新:2011年10月25日十六点00分38秒