刪除非空目錄需遞迴處理:先刪除子檔案/子目錄,最後刪除空目錄本身。
<?php
/**
* 遞迴刪除目錄及其所有內容
*
* @param string $dirPath 目錄路徑
* @return bool 成功刪除回傳 true
*/
function removeDir(string $dirPath): bool {
// 1. 驗證是否為目錄
if (!is_dir($dirPath)) {
return false;
}
// 2. 開啟目錄控制代碼
$handle = @opendir($dirPath);
if ($handle === false) {
return false; // 權限不足等
}
// 3. 遍歷目錄項目
while (($item = readdir($handle)) !== false) {
// 跳過 . 和 ..
if ($item === '.' || $item === '..') {
continue;
}
$fullPath = $dirPath . DIRECTORY_SEPARATOR . $item;
// 4. 遞迴處理:目錄則遞迴,檔案則刪除
if (is_dir($fullPath)) {
removeDir($fullPath);
} else {
@unlink($fullPath); // 抑制警告,由回傳值判斷
}
}
// 5. 關閉目錄控制代碼
closedir($handle);
// 6. 刪除現在已空的目錄
return @rmdir($dirPath);
}
?>
errors = []; $this->deletedFiles = $this->deletedDirs = 0; return $this->doRemove($path, $progress); } private function doRemove(string $path, callable $progress): bool { if (is_link($path)) { // 符號連結:只刪除連結本身,不跟隨 $result = @unlink($path); if ($result) $this->deletedFiles++; return $result; } if (!is_dir($path)) { $result = @unlink($path); if ($result) $this->deletedFiles++; if ($progress) $progress($path, 'file', $result); return $result; } $handle = @opendir($path); if (!$handle) { $this->errors[] = "無法開啟目錄: $path"; return false; } $success = true; while (($item = readdir($handle)) !== false) { if ($item === '.' || $item === '..') continue; $fullPath = $path . DIRECTORY_SEPARATOR . $item; $success &= $this->doRemove($fullPath, $progress); } closedir($handle); $result = @rmdir($path); if ($result) $this->deletedDirs++; if ($progress) $progress($path, 'dir', $result); return $success; } public function getStats(): array { return [ 'files' => $this->deletedFiles, 'dirs' => $this->deletedDirs, 'errors' => $this->errors, ]; } } // 使用 $remover = new DirectoryRemover(); $remover->remove('/var/www/cache', function($path, $type, $ok) { echo "[$type] $path : " . ($ok ? 'OK' : 'FAIL') . "\n"; }); print_r($remover->getStats());
isDir()) { removeDirModern($item->getPathname()); } else { @unlink($item->getPathname()); } } return @rmdir($dir); }
警告: 僅限受信任環境,必須嚴格驗證路徑防止命令注入。