close

最近在維護程式碼的時候,發現有一段刪除目錄以下全部檔案的 code。

 

@exec("rm -rf $dir");

 

讓我想到最近 GitLab 工程師最近誤刪資料庫的事件, 這種指令不能亂留在檔案裡面啊!

PHP rmdir 只能刪除空資料夾,unlink用刪除檔案,就找到了一種遞回刪除的方式。

 

方法

 

刪除目錄之前,先刪除所有檔案和目錄,每次判斷是檔案還是資料夾,是資料夾就遞迴執行。

 

#12 在執行同樣的 funciton deleteDir() 判斷

public static function deleteDir($dirPath)
{
    if (! is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            self::deleteDir($file); // recursion
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}

參考連結

 

--

轉自 https://clouding.city/php/delete-directory-files/

 

全站熱搜
創作者介紹
創作者 dizzy03 的頭像
dizzy03

碎碎念

dizzy03 發表在 痞客邦 留言(0) 人氣()