php文件目錄操作
目錄操作
is_dir ( $path ) 判斷當前路徑是否為目錄 ,返回布爾
opendir ( $path ) 打開路徑目錄,返回資源
readdir ( $handle ) 讀取當前打開目錄下一個文件,同時指針向前移動一位,返回字符串 (文件/目錄名)
closedir ( $handle ) 關閉當前打開目錄 返回布爾
getcwd ( ) 獲得當前工作目錄
rmdir 刪除目錄,刪除前必須先刪除目錄下所有文件和目錄
代碼:列出指定目錄下所有文件和文件名
function traversal_dir($path, $deep = 0) { if (is_dir($path)) { $handle = opendir($path); while (($file = readdir($handle)) !== false) { if ($file == . || $file == .. ) { continue; echo str_repeat( - , 2 * $deep) . $file . /br if (is_dir($path . / . $file)) { traversal_dir($path . / . $file, $deep + 1);traversal_dir( ./
文件操作
is_file ( $path ) :判斷指定 路徑是否為文件
file_exists ( $path ) : 檢查目錄或者文件是否存在
fopen ( $file ) :打開文件或者 URL 返回資源
fread ( resource $handle , int $length ) : 讀取文件,可指定長度
fwrite ( resource $handle , string $string [, int $length ] ) : 返回寫入字符串大小,如果指定了 length,當寫入了 length 個字節或者寫完了 string 以后,寫入就會停止,視乎先碰到哪種情況。
fgets ( resource $handle [, int $length ] ) : 讀取一行文本,length指定一行文本長度
fclose ( resource $handle ) : 關閉文件
basename ( $path ) : 返回指定路徑的文件名部分 返回String
dirname ( $path ) : 返回指定路徑的目錄名部分 返回string
路徑部分
操作部分
stat 獲得文件信息
判斷部分
filesize ( $path ) 獲得文件大小 int
filetype ( $path ) 獲得文件類型 string (可能值:fifo,char,dir,block,link,file 和 unknown)
rename ( string $oldname , string $newname [, resource $context ] ) 重命名或者移動 返回布爾
unlink ( $path ) 刪除文件 返回布爾
file_get_contents 將整個文件讀如一個字符串
file_put_contents 將一個字符串寫入文件
代碼:每執行一次文件,向文件頭部追加 Hello word
$path = ./hello.txt if (!file_exists($path)) { $handle = fopen($path, w+ fwrite($handle, Hello word . /r/n fclose($handle);} else { $handle = fopen($path, r $content = fread($handle, filesize($path)); $content = Hello word /r/n . $content; fclose($handle); $handle = fopen($path, w fwrite($handle, $content); fclose($handle);}
代碼:遍歷刪除文件夾及文件夾下所有文件
function traversal_delete_dir($path) { if (is_dir($path)) { $handle = opendir($path); while (($file = readdir($handle)) !== false) { if ($file == . || $file == .. ) { continue; if (is_dir($path . / . $file)) traversal_delete_dir($path . / . $file); } else { if (unlink($path . / . $file)) echo 刪除文件 . $file . 成功 closedir($handle); rmdir($path);traversal_delete_dir( ./shop_api
以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP !
相關推薦:
php的雙向隊列代碼
php生成xml數據的方法
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答