原始碼存在嚴重邏輯錯誤:遞迴呼叫參數未變更、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;
}
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() 處理// 建立測試結構
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 應存在且內容相同