PHP 遞迴刪除資料夾

看到很多教學文,都是用system指令去執行rm -Rf 把整個資料夾刪除 但如果php沒有開啟system指令的話要怎麼做呢 可以使用php的SPL的功能來完成遞迴刪除資料的動作 RecursiveIteratorIterator RecursiveDirectoryIterator 這兩個功能搭配在一起,就可以做出遞迴刪除檔案的動作了

   public function rmrf($targetFloder)
   {//delte tree like rm -Rf command line 
        $file = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($targetFloder), RecursiveIteratorIterator::CHILD_FIRST);
        foreach($files as $file){ 
            if ($file->isDir()){ 
                rmdir($file->getRealPath()); 
            }else{
 
                unlink($file->getRealPath());
 
            }
 
        }// foreach  
   }

發佈留言