首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 遞歸刪除目錄下文件(保留目錄結構)與刪除目錄連帶文件兩種模式實現

     編輯:PHP 綜合知識

模式一:刪除文件,保留目錄結構

function delFileUnderDir($dirName) {
    if ($handle = opendir($dirName)) {
        while (($item = readdir($handle)) !== false) {
            if ($item === '.' || $item === '..') continue;
            $path = "$dirName/$item";
            if (is_dir($path)) {
                delFileUnderDir($path); // 遞歸進入子目錄
            } else {
                if (unlink($path)) echo "已刪除文件:$path
"; } } closedir($handle); } }

模式二:刪除目錄及其所有內容(連帶刪除目錄本身)

function delDirAndFile($dirName) {
    if ($handle = opendir($dirName)) {
        while (($item = readdir($handle)) !== false) {
            if ($item === '.' || $item === '..') continue;
            $path = "$dirName/$item";
            if (is_dir($path)) {
                delDirAndFile($path);
            } else {
                if (unlink($path)) echo "已刪除文件:$path
"; } } closedir($handle); if (rmdir($dirName)) echo "成功刪除目錄:$dirName
"; } }

現代 SPL 寫法(推薦)

function deleteRecursive($path, $keepDir = false) {
    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST // 先刪子項
    );
    foreach ($it as $file) {
        $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
    }
    if (!$keepDir) rmdir($path);
}
  • CHILD_FIRST 確保先刪除文件再刪除目錄,避免「目錄非空」報錯。
  • $keepDir=true 對應模式一,false 對應模式二。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved