Home  >  Article  >  Backend Development  >  How to Recursively Copy an Entire Directory in PHP?

How to Recursively Copy an Entire Directory in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 06:53:30394browse

How to Recursively Copy an Entire Directory in PHP?

Copy Entire Directory Contents to Another in PHP

A user encountered an issue when attempting to copy an entire directory's contents to another location using the copy() function. The error message indicated that no stream was found and the placeholder . could not be located.

Solution:

The provided code only works for single-level directories. To copy directories with multiple levels, a more comprehensive approach is required:

<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>

Usage:

Provide the paths to the source and destination directories in the function call, and it will recursively copy all files and directories from the source to the destination.

The above is the detailed content of How to Recursively Copy an Entire Directory in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn