<?php
function listDir($dirname) {
$handle = opendir($dirname);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dirname . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
listDir($path); // 遞迴進入子目錄
} else {
echo $file . '<br>'; // 輸出檔案名
}
}
closedir($handle);
}
listDir('./final/factapplication');
?>
<?php
function copyDir($srcDir, $dstDir) {
// 建立目標目錄
if (!is_dir($dstDir)) {
mkdir($dstDir, 0755, true);
}
$handle = opendir($srcDir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$srcPath = $srcDir . DIRECTORY_SEPARATOR . $file;
$dstPath = $dstDir . DIRECTORY_SEPARATOR . $file;
if (is_dir($srcPath)) {
copyDir($srcPath, $dstPath); // 遞迴複製子目錄
} else {
copy($srcPath, $dstPath); // 複製檔案
}
}
closedir($handle);
}
copyDir('../fileupload', 'b'); // 將 ../fileupload 複製到 ./b
?>
<?php
function deleteDir($dirname) {
$handle = opendir($dirname);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dirname . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
deleteDir($path); // 遞迴刪除子目錄
} else {
unlink($path); // 刪除檔案
}
}
closedir($handle);
return rmdir($dirname); // 最後刪除空目錄本身
}
deleteDir('a');
?>
<?php
function dirSize($dirname) {
static $total = 0; // 靜態變數累加
$handle = opendir($dirname);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dirname . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
dirSize($path); // 遞迴計算子目錄
} else {
$total += filesize($path); // 累加檔案大小
}
}
closedir($handle);
return $total;
}
echo '目錄大小:' . dirSize('a') . ' bytes';
echo '(約 ' . round(dirSize('a') / 1024 / 1024, 2) . ' MB)';
?>
| 操作 | 核心函數 | 遞迴關鍵點 |
|---|---|---|
| 列舉 | opendir/readdir/is_dir | 檔案輸出、目錄遞迴 |
| 複製 | mkdir/copy | 先建目錄、再遞迴/複製檔案 |
| 刪除 | unlink/rmdir | 先刪檔案/子目錄、最後刪空目錄 |
| 計算大小 | filesize | 靜態變數跨遞迴層級累加 |
<?php
// 列舉所有檔案
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
);
foreach ($files as $file) {
echo $file->getPathname() . '<br>';
}
// 計算總大小
$totalSize = 0;
foreach ($files as $file) {
if ($file->isFile()) $totalSize += $file->getSize();
}
// 刪除目錄(需自行實作遞迴刪除,SPL 無內建刪除目錄樹功能)
?>
SPL 寫法更符合現代 PHP 風格,但刪除操作仍需自行實作遞迴邏輯。