php 刪除指定檔案夾

來源:互聯網
上載者:User

標籤:sch   lang   win   upload   檔案操作   刪除檔案   問題   sed   tin   

php 刪除指定檔案夾1、前言

目標:php刪除一個指定目錄

所使用的的php函數:is_dir,opendir,readdir,scandir,rmdir,closedir,等等(註:其他檔案操作函數也可以完成,這裡只列舉了本次使用的函數)

2、相關函數介紹

php檔案操作的方法大致相同,已經在上一篇介紹過了,這裡就不在重複介紹,這裡就介紹一個新函數 

rmdir

詳情參考:http://www.w3school.com.cn/php/func_filesystem_rmdir.asp

 

其他函數請參考上一篇: http://www.cnblogs.com/ImCehnyx/p/7214598.html

3、代碼構成

 

** * [delAllFile description] 刪除指定目錄 * @param [type] $dirName [description] 目錄 * @param [type] $file [description] 記錄的過程檔案 * @param integer $type [description] 第一次預設開啟新檔案,第二次調用不開啟 * @return [type] [description] */public function delAllFile($dirName, $file, $type = 1) {$re = $this->checkDir($dirName);//預設第一次開啟檔案if($type){$file = fopen($file, ‘w‘);//開啟記錄檔}if($re){$this->delFile($dirName, $file);}else{fwrite($file,"{$dirName}清理完成\r\n");}}/** * [checkDir description] 檢測檔案夾是否為空白,為空白直接刪除 * @param [type] $dirName [description] 檔案夾名 * @return [type] [description] */private function checkDir($dirName) {$a = scandir($dirName);//列出 images 目錄中的檔案和目錄://只包含.和..目錄的檔案夾為空白檔案夾if(sizeof($a) == 2){rmdir($dirName);return false;}return true;}/** * [delFile description] 上傳檔案的方法 * @param [type] $dirName [description] 目錄 * @param [type] $file [description] 記錄的檔案 * @return [type] [description] */private function delFile($dirName, $file) {$dh = openDir($dirName);while($handle = readdir($dh)){if($handle == ‘.‘ || $handle == ‘..‘) {continue;}$resource = $dirName.‘/‘.$handle;//判斷是否是檔案夾if(is_dir($resource)) {//判斷檔案夾是否為空白$re = $this->checkDir($dirName);if($re){$this->delAllFile($resource, $file, 0);}else{fwrite($file,"{$resource}清理完成\r\n");continue;}}else{unlink($resource);}}//關掉資源,刪除目錄closedir($dh);//關閉目錄資源 fwrite($file,"{$dirName}清理完成\r\n"); rmdir($dirName);//刪除空目錄 }
然而,上面的代碼遇到子目錄層級高的時候,就容易出現一個警告,導致目錄無法刪除

 

故對於層級高的子集,需要在最後加上一個迴圈判斷,來判斷是否可以刪除,來避免這個錯誤

 

// //關掉資源,刪除目錄// closedir($dh);//關閉目錄資源  // fwrite($file,"{$dirName}清理完成\r\n");//rmdir($dirName);//刪除空目錄 //每次目錄層級高了就報錯,故加個迴圈處理$i = 1;while($i){ $re = $this->checkDir($dirName); echo "$dirName $i 次<br/><hr/>"; $i++; if(!$re){ $i = 0; closedir($dh);//關閉目錄資源  fwrite($file,"{$dirName}清理完成\r\n"); }}

 

加上這層可以避免無法刪除的情況(有時候刪不掉是許可權的問題)

4、結語

刪除一個目錄相對比較簡單,基本步驟為:

1、判斷是否是目錄,是目錄則遞迴調用自己,否則直接刪除檔案;

2、判斷目錄是否為空白,不為空白 rmdir會拋出錯誤;

3、檔案許可權的問題(window,這個不是什麼問題) 

php 刪除指定檔案夾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.