Recursive Copy of Directory Recursive Copy of Directory php php

Recursive Copy of Directory


Try something like this:

$source = "dir/dir/dir";$dest= "dest/dir";mkdir($dest, 0755);foreach ( $iterator = new \RecursiveIteratorIterator(  new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),  \RecursiveIteratorIterator::SELF_FIRST) as $item) {  if ($item->isDir()) {    mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathname());  } else {    copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathname());  }}

Iterator iterate through all folders and subfolders and make copy of files from $source to $dest


Could I suggest that (assuming it's a *nix VPS) that you just do a system call to cp -r and let that do the copy for you.


I have changed Joseph's code (below), because it wasn't working for me. This is what works:

function cpy($source, $dest){    if(is_dir($source)) {        $dir_handle=opendir($source);        while($file=readdir($dir_handle)){            if($file!="." && $file!=".."){                if(is_dir($source."/".$file)){                    if(!is_dir($dest."/".$file)){                        mkdir($dest."/".$file);                    }                    cpy($source."/".$file, $dest."/".$file);                } else {                    copy($source."/".$file, $dest."/".$file);                }            }        }        closedir($dir_handle);    } else {        copy($source, $dest);    }}

[EDIT] added test before creating a directory (line 7)