<?php
header('Content-Type: text/html; charset=utf-8');
function delFile($fpath) {
$filesize = [];
$filepath = iconv('gb2312', 'utf-8', $fpath); // 顯示用編碼轉換
if (is_dir($fpath)) {
if ($dh = opendir($fpath)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..') {
$filesize[] = delFile($fpath . '/' . $file);
}
}
closedir($dh);
}
// 嘗試刪除空目錄
$filesize['file'] = 0;
if (@rmdir($fpath) === true) {
echo "{$filepath}................刪除成功<br>\n";
} else {
echo "{$filepath}................刪除失敗<br>\n";
}
} else {
if (is_file($fpath)) {
$fsize = filesize($fpath);
$filesize[] = $fsize;
if (@unlink($fpath) === true) {
echo "{$filepath}...{$fsize}K................刪除成功<br>\n";
} else {
echo "{$filepath}...{$fsize}K................刪除失敗<br>\n";
}
}
}
return $filesize;
}
function getArrSum(&$arr) {
if (is_array($arr)) {
foreach ($arr as &$value) {
$value = getArrSum($value);
}
return array_sum($arr);
}
return $arr;
}
// 測試入口
$fpath = 'D:/test'; // 請改為實際路徑
$filesize = delFile($fpath);
$size = getArrSum($filesize);
printf('為您節省:%.3fM 空間', $size / (1024 * 1024));
?>
目錄:先遞歸清空內容,再 rmdir();文件:直接 unlink()。@ 抑制警告,由返回值判斷成敗。
Windows 下文件系統常為 GB2312,iconv() 轉 UTF-8 供頁面顯示,避免中文亂碼。
getArrSum() 遞歸展開嵌套數組,配合 array_sum() 獲取總位元組數。
在 D 槽建立 test 目錄並放入任意文件/子目錄,執行腳本即可見效果。
RecursiveDirectoryIterator)或分批處理。