PHP - Copy the entire contents of a directory to another directory

By IncludeHelp Last updated : January 10, 2024

Problem statement

Write a PHP program to copy the entire contents of a directory to another directory.

Copying the entire contents of a directory to another directory

  • Write a recursive function.
  • Open the source directory using the opendir() function.
  • Make the target directory (if does not exists) using the @mkdir() function.
  • Loop through the files in the source directory, and read the directory using the readdir() function.
  • Check the conditions for file existence inside the loop.
  • If files exist, copy files from source path to target path.
  • Call the function recursively.

PHP program to copy the entire contents of a directory to another directory

Here, are copying all files from the source directory which is (E:/samples/collection) to another (E:/php_programs/new).

<?php
function copy_all_files($source_dir, $target_dir)
{
    // opening the source directory
    $dir_obj = opendir($source_dir);

    // creating targeted directory if it does not exist
    @mkdir($target_dir);

    while ($file = readdir($dir_obj)) {
        if ($file != "." && $file != "..") {
            if (is_dir($source_dir . "/" . $file)) {
                // Recursive call
                copy_all_files(
                    $source_dir . "/" . $file,
                    $target_dir . "/" . $file
                );
            } else {
                copy($source_dir . "/" . $file, $target_dir . "/" . $file);
            }
        }
    }
    closedir($dir_obj);
}

// Main code
$source_dir = "E:/samples/collection";
$target_dir = "E:/php_programs/new";

copy_all_files($source_dir, $target_dir);
?>

More PHP File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.