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

Given a directory and the task is to copy the content of the directory to another directory using PHP functions. There are many functions used to copy the content of one directory to another.

Used Functions:

Example 1: This example uses readdir() function to read files from the source directory.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
function custom_copy($src, $dst) { 
  
    // open the source directory
    $dir = opendir($src); 
  
    // Make the destination directory if not exist
    @mkdir($dst); 
  
    // Loop through the files in source directory
    while( $file = readdir($dir) ) { 
  
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) 
            
  
                // Recursively calling custom copy function
                // for sub directory 
                custom_copy($src . '/' . $file, $dst . '/' . $file); 
  
            
            else
                copy($src . '/' . $file, $dst . '/' . $file); 
            
        
    
  
    closedir($dir);
  
$src = "C:/xampp/htdocs/geeks";
  
$dst = "C:/xampp/htdocs/gfg";
  
custom_copy($src, $dst);
  
?>
chevron_right

Output:

Example 2: This example uses scandir() function to read files from the source directory.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
    
function custom_copy($src, $dst) { 
   
    // open the source directory
    $dir = opendir($src); 
   
    // Make the destination directory if not exist
    @mkdir($dst); 
   
    // Loop through the files in source directory
    foreach (scandir($src) as $file) { 
   
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) 
            
   
                // Recursively calling custom copy function
                // for sub directory 
                custom_copy($src . '/' . $file, $dst . '/' . $file); 
   
            
            else
                copy($src . '/' . $file, $dst . '/' . $file); 
            
        
    
   
    closedir($dir);
}  
  
$src = "C:/xampp/htdocs/geeks";
  
$dst = "C:/xampp/htdocs/gfg";
  
custom_copy($src, $dst);
  
?>
chevron_right

Output:





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :