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

How to Recursively Copy an Entire Directory Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-30 19:31:03263browse

How to Recursively Copy an Entire Directory Using PHP?

How to Recursively Copy an Entire Directory Using PHP

Copying the entire contents of a directory to another location can be a common task in PHP programming. While the copy function can be used for a flat directory structure, it may encounter limitations when dealing with multiple levels of directories.

Dave asked about how to copy the contents of a directory using copy ("old_location/*.*","new_location/"), but the provided code outputs an error stating that the stream cannot be found and *.* is not found.

A solution that addresses this issue is to use a recursive function like the one below:

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

By utilizing recursion, this function can traverse the directory structure and create child directories if necessary. It checks the file type for each item in the directory and recursively calls itself to copy files or create directories as needed.

The above is the detailed content of How to Recursively Copy an Entire Directory Using 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