當嘗試將目錄內容複製到另一個位置時,程式碼copy ("old_location/*.*"," new_location/" ) 可能會遇到錯誤,指示未找到該流。當在複製函數中單獨使用星號 (*) 時,可能會發生這種情況。
為了有效複製目錄的全部內容(包括其子目錄和文件),我們可以使用以下遞歸函數:
<code class="php">function recurseCopy( string $sourceDirectory, string $destinationDirectory, string $childFolder = '' ): void { // Open the source directory $directory = opendir($sourceDirectory); // Check if the destination directory exists, if not, create it if (is_dir($destinationDirectory) === false) { mkdir($destinationDirectory); } // If there's a child folder specified, create it if it doesn't exist if ($childFolder !== '') { if (is_dir("$destinationDirectory/$childFolder") === false) { mkdir("$destinationDirectory/$childFolder"); } // Loop through the files in the source directory while (($file = readdir($directory)) !== false) { // Ignore current and parent directories if ($file === '.' || $file === '..') { continue; } // If the current file is a directory, recursively copy it if (is_dir("$sourceDirectory/$file") === true) { recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file"); } // If it's a file, simply copy it else { copy("$sourceDirectory/$file", "$destinationDirectory/$childFolder/$file"); } } // Close the source directory closedir($directory); // Recursion ends here return; } // Loop through the files in the source directory while (($file = readdir($directory)) !== false) { // Ignore current and parent directories if ($file === '.' || $file === '..') { continue; } // If the current file is a directory, recursively copy it if (is_dir("$sourceDirectory/$file") === true) { recurseCopy("$sourceDirectory/$file", "$destinationDirectory/$file"); } // If it's a file, simply copy it else { copy("$sourceDirectory/$file", "$destinationDirectory/$file"); } } // Close the source directory closedir($directory); }</code>
透過使用這個遞歸函數,我們可以有效地將一個目錄的全部內容複製到另一個位置,確保所有子目錄和檔案都正確傳輸。
以上是如何使用 PHP 遞歸複製目錄的內容?的詳細內容。更多資訊請關注PHP中文網其他相關文章!