1. 程式人生 > >php刪除資料夾(臨時檔案)程式碼

php刪除資料夾(臨時檔案)程式碼

      我們有時候需要刪除剛生成的臨時檔案,比如上傳圖片或者生成圖片的時候,我們需要現在本地儲存起來,然後再上傳到圖片伺服器。當圖片上傳到伺服器之後,那本地儲存的圖片就沒用了,為了避免專案檔案過大,所以刪除本地的圖片檔案的就變得很有必要。

直接分享一段程式碼:

//需要傳兩個引數,一個是我們需要刪除的檔案路徑,比如:
  $path2= "./upload/picture/";
      $this->delDirAndFile($path,true);

//這是刪除的方法
  public function delDirAndFile($path, $delDir = true) {
     if (is_array($path)) {
       foreach ($path as $subPath)
         $this->delDirAndFile($subPath, $delDir);
     }
     if (is_dir($path)) {
       $handle = opendir($path);
       if ($handle) {
         while (false !== ( $item = readdir($handle) )) {
           if ($item != "." && $item != "..")
             is_dir("$path/$item") ?  $this->delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
         }
         closedir($handle);
         if ($delDir)
           return rmdir($path);
       }
     } else {
       if (file_exists($path)) {
         return unlink($path);
       } else {
         return FALSE;
       }
     }
     clearstatcache();
   }

以上就刪除資料夾或者檔案的程式碼部分。(順便吐槽一句,編輯器的程式碼顏色看起來真難看。。。)

end