本文示範如何以遞迴函式遍歷目錄並刪除所有檔案與子目錄,稍加修改即可轉為複製功能。
<?php
function mover($src, $dst) {
$handle = opendir($src);
if (!is_dir($dst)) mkdir($dst, 0755);
while ($file = readdir($handle)) {
if ($file !== "." && $file !== "..") {
$srcPath = $src . "/" . $file;
$dstPath = $dst . "/" . $file;
if (is_dir($srcPath)) {
mover($srcPath, $dstPath); // 遞迴處理子目錄
} else {
copy($srcPath, $dstPath);
unlink($srcPath); // 僅需複製時註解此行
}
}
}
closedir($handle);
rmdir($src); // 刪除空來源目錄
}
?>
原理:opendir 開啟目錄、readdir 逐一讀取、is_dir 判斷類型、遞迴呼叫自身處理子層,最後 rmdir 移除空目錄。