首頁  >  文章  >  後端開發  >  如何使用 PHP 遞歸複製目錄的內容?

如何使用 PHP 遞歸複製目錄的內容?

Patricia Arquette
Patricia Arquette原創
2024-10-29 10:30:291079瀏覽

How to Copy a Directory's Contents Using PHP Recursively?

使用PHP 複製目錄內容

當嘗試將目錄內容複製到另一個位置時,程式碼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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn