一、檔案函數庫
1、readfile()函數讀取檔案,並把它寫入緩衝。
建立一個01.txt,寫入一下內容
php readfile
建立一個php檔案
<?phpecho readfile("01.txt");?>
2、fopen開啟檔案
fopen()函數的第一個參數表示要操作的檔案,第二個參數表示開啟檔案的模式。
<?php$file = fopen("01.txt", "r") or die("出現錯誤。");echo fread($file, filesize("01.txt"));fclose($file);?>
| 模式 |
描述 |
| r |
開啟檔案為唯讀。檔案指標在檔案的開頭開始。 |
| w |
開啟檔案為唯寫。刪除檔案的內容或建立一個新的檔案,如果它不存在。檔案指標在檔案的開頭開始。 |
| a |
開啟檔案為唯寫。檔案中的現有資料會被保留。檔案指標在檔案結尾開始。建立新的檔案,如果檔案不存在。 |
| x |
建立新檔案為唯寫。返回 FALSE 和錯誤,如果檔案已存在。 |
| r+ |
開啟檔案為讀/寫、檔案指標在檔案開頭開始。 |
| w+ |
開啟檔案為讀/寫。刪除檔案內容或建立新檔案,如果它不存在。檔案指標在檔案開頭開始。 |
| a+ |
開啟檔案為讀/寫。檔案中已有的資料會被保留。檔案指標在檔案結尾開始。建立新檔案,如果它不存在。 |
| x+ |
建立新檔案為讀/寫。返回 FALSE 和錯誤,如果檔案已存在。 |
3、fread()讀取檔案
fread()第一個參數表示待讀取的檔案(就是fopen()的指標),第二個參數規定待讀取的最大位元組數。
4、fclose()關閉檔案
關閉檔案,節省電腦資源
5、fgets()讀取單行檔案
調用fgets()函數後,檔案指標會移動到下一行
6、feof()遍曆未知長度的資料很有用。
7、fget()函數用於從檔案中讀取但個字元。
檔案指標會自動下移
8、fwirte()寫入檔案
第一個參數表示要寫入的檔案,第二個參數表示要寫入的內容。
9、file_get_contents() 整個檔案讀入到字串。
二、目錄操作
1.目錄讀取、opendir()、readdir()、closedir()
<?php$dir = opendir("filedir/");while ($filelist = readdir($dir)) {echo $filelist . "<br />";}closedir($dir);?>
dirname($path)返迴文件目錄部分
basename($path)返迴文件名稱部分
disk_free_space($path)返迴文件所在分區的大小
2.php拷貝一個目錄操作
<?phpfunction copydir($sourceDir, $destDir){ if (!is_dir($sourceDir)) { return false; } if (!is_dir($destDir)) { if (!mkdir($destDir)) { return false; } } $dir = opendir($sourceDir); if (!$dir) { return false; } while(false !== ($file=readdir($dir))) { if ($file != '.' && $file != '..') { if (is_dir($sourceDir.'/'.$file)) { if (!copydir($sourceDir.'/'.$file, $destDir.'/'.$file)) { return false; } }else { if (!copy($sourceDir.'/'.$file, $destDir.'/'.$file)) { return false; } } } } closedir($dir); return true;}copydir('./test1', './test2');
3.php刪除一個目錄
<?phpfunction deldir($dir){ $dh = opendir($dir); while ($file = readdir($dh)) { if ($file != '.' && $file != '..') { $fullpath = $dir.'/'.$file; if (!is_dir($fullpath)) { unlink($fullpath); } else { deldir($fullpath); } } } closedir($dh); if (rmdir($dir)) { return true; } return false;}deldir('./test2');