專案部署、備份、快取清理常需「整個目錄樹」複製。PHP 無內建單一函式支援遞迴複製目錄,需自行結合 opendir、mkdir、copy 實作。本文提供生產級函式,涵蓋權限保留、錯誤處理、符號連結、效能優化等關鍵細節。
<?php
/**
* 遞迴複製目錄樹
*
* @param string $srcDir 來源目錄(絕對路徑)
* @param string $dstDir 目標目錄(絕對路徑)
* @param array $options 選項:
* - preserve_permissions (bool) 保留檔案/目錄權限,預設 true
* - preserve_timestamps (bool) 保留修改時間,預設 true
* - follow_symlinks (bool) 複製符號連結本身而非目標,預設 false
* - verbose (bool) 回傳詳細統計,預設 false
* @return array|bool 成功回傳統計陣列,失敗回傳 false
*/
function recursiveCopyDir(string $srcDir, string $dstDir, array $options = []): array|bool
{
$opts = array_merge([
'preserve_permissions' => true,
'preserve_timestamps' => true,
'follow_symlinks' => false,
'verbose' => false,
], $options);
// 正規化路徑
$srcDir = rtrim(realpath($srcDir), DIRECTORY_SEPARATOR);
if ($srcDir === false) {
trigger_error("來源目錄不存在:$srcDir", E_USER_WARNING);
return false;
}
$dstDir = rtrim($dstDir, DIRECTORY_SEPARATOR);
$ds = DIRECTORY_SEPARATOR;
$stats = ['dirs' => 0, 'files' => 0, 'bytes' => 0, 'errors' => []];
// 內部遞迴函式
$copy = function ($src, $dst) use (&$copy, $ds, $opts, &$stats) {
// 建立目標目錄
if (!is_dir($dst)) {
$oldmask = umask(0);
if (!mkdir($dst, 0777, true)) {
$stats['errors'][] = "建立目錄失敗:$dst";
umask($oldmask);
return false;
}
umask($oldmask);
$stats['dirs']++;
}
// 保留目錄權限與時間
if ($opts['preserve_permissions']) {
@chmod($dst, fileperms($src) & 07777);
}
if ($opts['preserve_timestamps']) {
@touch($dst, filemtime($src));
}
$handle = @opendir($src);
if (!$handle) {
$stats['errors'][] = "無法開啟目錄:$src";
return false;
}
while (($entry = readdir($handle)) !== false) {
if ($entry === '.' || $entry === '..') continue;
$srcPath = $src . $ds . $entry;
$dstPath = $dst . $ds . $entry;
// 處理符號連結
if (is_link($srcPath)) {
if ($opts['follow_symlinks']) {
$target = readlink($srcPath);
if (!symlink($target, $dstPath)) {
$stats['errors'][] = "建立符號連結失敗:$dstPath -> $target";
}
}
continue;
}
if (is_dir($srcPath)) {
$copy($srcPath, $dstPath);
} elseif (is_file($srcPath)) {
if (!@copy($srcPath, $dstPath)) {
$stats['errors'][] = "複製檔案失敗:$srcPath -> $dstPath";
continue;
}
$stats['files']++;
$stats['bytes'] += filesize($srcPath);
if ($opts['preserve_permissions']) {
@chmod($dstPath, fileperms($srcPath) & 07777);
}
if ($opts['preserve_timestamps']) {
@touch($dstPath, filemtime($srcPath));
}
}
}
closedir($handle);
return true;
};
$ok = $copy($srcDir, $dstDir);
return $ok ? $stats : false;
}
// 使用範例
$result = recursiveCopyDir(
'/var/www/project',
'/backup/project_' . date('Ymd_His'),
['verbose' => true]
);
if ($result) {
echo "複製完成:{$result['dirs']} 個目錄、{$result['files']} 個檔案、"
. number_format($result['bytes'] / 1024 / 1024, 2) . " MB\n";
if ($result['errors']) {
echo "警告:" . count($result['errors']) . " 個錯誤\n";
print_r($result['errors']);
}
} else {
echo "複製失敗\n";
}
?>
is_link() 檢測並選擇略過或複製連結本身。mkdir()、copy() 可能因權限失敗。方案:umask(0) 暫時移除遮罩,錯誤記錄不中斷流程。<?php
function recursiveCopyDirIterative(string $src, string $dst): bool
{
$src = rtrim(realpath($src), DIRECTORY_SEPARATOR);
$dst = rtrim($dst, DIRECTORY_SEPARATOR);
if ($src === false) return false;
$stack = [[$src, $dst]];
$ds = DIRECTORY_SEPARATOR;
while ($stack) {
[$curSrc, $curDst] = array_pop($stack);
if (!is_dir($curDst)) {
@mkdir($curDst, 0777, true);
@chmod($curDst, fileperms($curSrc) & 07777);
@touch($curDst, filemtime($curSrc));
}
$handle = @opendir($curSrc);
if (!$handle) continue;
while (($entry = readdir($handle)) !== false) {
if ($entry === '.' || $entry === '..') continue;
$s = $curSrc . $ds . $entry;
$d = $curDst . $ds . $entry;
if (is_dir($s)) {
$stack[] = [$s, $d]; // 壓入堆疊,稍後處理
} elseif (is_file($s)) {
@copy($s, $d);
@chmod($d, fileperms($s) & 07777);
@touch($d, filemtime($s));
}
}
closedir($handle);
}
return true;
}
?>
Filesystem::mirror($src, $dst),功能完善、測試完備。$fs->copyDir($src, $dst)。cp -a、rsync -a;Windows robocopy /MIR。透過 exec()/proc_open() 呼叫,效能最強、功能最全(保留 ACL、延伸屬性、稀疏檔等)。掌握遞迴複製目錄的核心邏輯,不僅能應對無庫環境,更能深入理解檔案系統操作的細節與陷阱。