Skip to content

How to copy files recursively using PHP ?

In my previous post , i just wrote about copying file from one folder to another folder. Now i want to show you one simple example for recursively copying files from one directory to another directory using DirectoryIterator Class.It’s provides a simple interface for viewing the contents of filesystem directories.

Below is my function , which will copy the entire file system to the new given destination folder recursively.

function copyTree($source,$destination) {
    // Add directory separator at the end
    $source = rtrim($source, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
    $destination = rtrim($destination, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
    
 
    if(!is_dir($source) && !is_readable($source)) {
        return false;
    }
    
    if(!is_dir($destination)) {
        if(!mkdir($destination)) {
            return false;
        }
    }
    
    $dirIteratorObject = new DirectoryIterator($source);
    
     foreach ($dirIteratorObject as $info ) {
        if ($info->isFile ()) {
            copy($info->getFileInfo(), $destination.$info->getFilename());
        } elseif($info->isDot() && $info->isDir()) {
            copyTree($info->getRealPath(), "$destination.$info");
        }
     }
}

That’s it!.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments