PHP文件操作常見錯(cuò)誤:
- 編輯錯(cuò)誤的文件
- 被垃圾數(shù)據(jù)填滿硬盤
- 意外刪除文件內(nèi)容
一、 readfile() 函數(shù)
readfile() 函數(shù)讀取文件,并把它寫入輸出緩沖。
假設(shè)我們有一個(gè)名為 "webdictionary.txt" 的文本文件,存放在服務(wù)器上
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
讀取此文件并寫到輸出流的 PHP 代碼如下:
<?php
echo readfile("webdictionary.txt");
?>
二、fopen() 函數(shù)
打開文件的更好的方法是通過(guò) fopen() 函數(shù)。此函數(shù)為您提供比 readfile() 函數(shù)更多的選項(xiàng)。
仍然假設(shè)我們有一個(gè)名為 "webdictionary.txt" 的文本文件,存放在服務(wù)器上
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
讀取此文件:
fopen() 的第一個(gè)參數(shù)包含被打開的文件名,第二個(gè)參數(shù)規(guī)定打開文件的模式。
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");//如果不能打開文件,會(huì)輸出相應(yīng)信息
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile); //最后關(guān)閉文件
?>

三、fread()函數(shù)
fread() 函數(shù)讀取打開的文件。
fread() 的第一個(gè)參數(shù)包含待讀取文件的文件名,第二個(gè)參數(shù)規(guī)定待讀取的最大字節(jié)數(shù)。
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
如上:代碼中把 "webdictionary.txt" 文件讀至結(jié)尾: fread($myfile,filesize("webdictionary.txt"));
四、fclose() 函數(shù)
fclose() 函數(shù)用于關(guān)閉打開的文件。
注釋:用完文件后把它們?nèi)筷P(guān)閉是一個(gè)良好的編程習(xí)慣。否則會(huì)占用服務(wù)器資源。
語(yǔ)法:fclose() 需要待關(guān)閉文件的名稱(或者存有文件名的變量):
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
五、feof() 函數(shù)
feof() 函數(shù)檢查是否已到達(dá) "end-of-file" (EOF)。
feof() 對(duì)于遍歷未知長(zhǎng)度的數(shù)據(jù)很有用。
下例逐行讀取 "webdictionary.txt" 文件,直到 end-of-file:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// 輸出一行直到 end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
六、fgetc() 函數(shù)
fgetc() 函數(shù)用于從文件中讀取單個(gè)字符。
下例逐字符讀取 "webdictionary.txt" 文件,直到 end-of-file:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// 輸出單字符直到 end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
注釋:在調(diào)用 fgetc() 函數(shù)之后,文件指針會(huì)移動(dòng)到下一個(gè)字符。