萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 目錄操作四大核心功能實作:列舉、複製、刪除、計算大小

1. 遞迴列舉目錄下所有檔案

<?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');
?>

2. 遞迴複製整個目錄結構

<?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
?>

3. 遞迴刪除目錄及其所有內容

<?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');
?>

4. 遞迴計算目錄總大小

<?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靜態變數跨遞迴層級累加

現代化替代方案(SPL)

<?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 風格,但刪除操作仍需自行實作遞迴邏輯。

copyright © 萬盛學電腦網 all rights reserved