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

How to Recursively Copy an Entire Directory in PHP?

Linda Hamilton
Release: 2024-10-29 06:53:30
Original
470 people have browsed it

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>
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template