PHP: How to copy all files from one directory to another

Generating Random String Using PHP

I will guide you to copy all files & sub directories of the directory to another directory using PHP copy() function. There are many other functions used to copy the content of one directory to another.

  • copy() Function
  • opendir() Function
  • is_dir() Function
  • scandir( ) Function
  • readdir() Function

PHP code for copy multiple files from one folder to another

<?php 
  
function recursive_files_copy($source_dir, $destination_dir) 
{ 
  // Open the source folder / directory 
  $dir = opendir($source_dir);  

  // Create a destination folder / directory if not exist 
  @mkdir($destination_dir);  

  // Loop through the files in source directory 
  while($file = readdir($dir)) 
  {
    // Skip . and .. 
    if(($file != '.') && ($file != '..')) 
    {  
      // Check if it's folder / directory or file 
      if(is_dir($source_dir.'/'.$file))  
      {  
        // Recursively calling this function for sub directory  
        recursive_files_copy($source_dir.'/'.$file, $destination_dir.'/'.$file); 
      }  
      else 
      {  
        // Copying the files
        copy($source_dir.'/'.$file, $destination_dir.'/'.$file);  
      }  
    }  
  }  

  closedir($dir); 
}  

$source_dir = "/home/bg/folder_1"; 
  
$destination_dir = "/home/bg/folder_2"; 
  
recursive_files_copy($source_dir, $destination_dir); 
  
?> 

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *