指令copy ("old_location/*.*","new_lo/" ) 失敗,因為copy() 函數無法直接辨識通配符(*.*)。
複製整個目錄的內容,包括子目錄和文件, 遞歸複製函數是必要的。以下是範例:
<code class="php">function recurseCopy(string $sourceDirectory, string $destinationDirectory, string $childFolder = ''): void { $directory = opendir($sourceDirectory); if (is_dir($destinationDirectory) === false) { mkdir($destinationDirectory); } if ($childFolder !== '') { if (is_dir("$destinationDirectory/$childFolder") === false) { mkdir("$destinationDirectory/$childFolder"); } while (($file = readdir($directory)) !== false) { if ($file === '.' || $file === '..') { continue; } if (is_dir("$sourceDirectory/$file") === true) { recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file"); } else { copy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file"); } } closedir($directory); return; } while (($file = readdir($directory)) !== false) { if ($file === '.' || $file === '..') { continue; } if (is_dir("$sourceDirectory/$file") === true) { recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$file"); } else { copy("$sourceDirectory/$file", "$destinationDirectory/$file"); } } closedir($directory); }</code>
要使用此函數,請使用來源目錄、目標目錄和可選子資料夾(如果需要)來呼叫它。
<code class="php">recurseCopy("old_location", "new_location");</code>
以上是如何使用 PHP 複製目錄內容?的詳細內容。更多資訊請關注PHP中文網其他相關文章!