萬盛學電腦網

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

PHP 遞迴複製目錄完整函數實作與改進版

原始教學碼問題分析

原始碼存在嚴重邏輯錯誤:遞迴呼叫參數未變更、copy() 參數錯誤、未處理 . .. 目錄、無錯誤處理。

正確版:遞迴複製目錄

function copyDirectory(string $source, string $dest, bool $overwrite = true): bool {
    // 1. 來源必須是目錄
    if (!is_dir($source)) {
        trigger_error("來源 '$source' 不是目錄", E_USER_WARNING);
        return false;
    }
    
    // 2. 目的地若是檔案則失敗
    if (file_exists($dest) && !is_dir($dest)) {
        trigger_error("目的地 '$dest' 已存在且非目錄", E_USER_WARNING);
        return false;
    }
    
    // 3. 建立目的目錄
    if (!is_dir($dest)) {
        if (!mkdir($dest, 0755, true) && !is_dir($dest)) {
            trigger_error("無法建立目錄 '$dest'", E_USER_ERROR);
            return false;
        }
    }
    
    // 4. 開啟目錄讀取
    $dh = opendir($source);
    if (!$dh) return false;
    
    $success = true;
    while (($file = readdir($dh)) !== false) {
        // 跳過 . 和 ..
        if ($file === '.' || $file === '..') continue;
        
        $srcPath = $source . DIRECTORY_SEPARATOR . $file;
        $destPath = $dest . DIRECTORY_SEPARATOR . $file;
        
        if (is_dir($srcPath)) {
            // 遞迴複製子目錄
            if (!copyDirectory($srcPath, $destPath, $overwrite)) {
                $success = false;
            }
        } else {
            // 複製檔案
            if ($overwrite || !file_exists($destPath)) {
                if (!copy($srcPath, $destPath)) {
                    trigger_error("複製失敗: $srcPath → $destPath", E_USER_WARNING);
                    $success = false;
                }
            }
        }
    }
    closedir($dh);
    return $success;
}

現代替代方案:RecursiveIteratorIterator

function copyDirectoryModern(string $source, string $dest, bool $overwrite = true): void {
    $source = realpath($source);
    if (!$source || !is_dir($source)) throw new InvalidArgumentException("來源目錄不存在");
    
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $item) {
        $relativePath = $iterator->getSubPathName();
        $targetPath = $dest . DIRECTORY_SEPARATOR . $relativePath;
        
        if ($item->isDir()) {
            if (!is_dir($targetPath)) {
                mkdir($targetPath, 0755, true);
            }
        } else {
            if ($overwrite || !file_exists($targetPath)) {
                copy($item->getPathname(), $targetPath);
            }
        }
    }
}

進階需求考量

  • 權限保留:chmod($destPath, $item->getPerms())
  • 時間戳保留:touch($destPath, $item->getMTime())
  • 符號連結:判斷 $item->isLink() 用 symlink() 處理
  • 大量檔案:考慮非同步/佇列處理,避免逾時
  • 進度回呼:加入 callback 參數報告進度

測試範例

// 建立測試結構
mkdir('src/a/b', 0755, true);
file_put_contents('src/a/file1.txt', 'content1');
file_put_contents('src/a/b/file2.txt', 'content2');

copyDirectory('src', 'dst');
// dst/a/file1.txt, dst/a/b/file2.txt 應存在且內容相同
copyright © 萬盛學電腦網 all rights reserved