How to implement a script that copies directories with all the contents?

    2 answers 2

    Try this:

    $sourceDir = 'path/to/source/dir'; $destDir = 'path/to/dest/dir'; if (!file_exists($destDir)) { mkdir($destDir, 0755, true); } $dirIterator = new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS); $iterator = new RecursiveIteratorIterator($dirIterator, RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $object) { $destPath = $destDir . DIRECTORY_SEPARATOR . $iterator->getSubPathName(); ($object->isDir()) ? mkdir($destPath) : copy($object, $destPath); } 

      Here is an example of the function:

       function copydirect($source, $dest, $over=false) { if(!is_dir($dest)) mkdir($dest); if($handle = opendir($source)) { while(false !== ($file = readdir($handle))) { if($file != '.' && $file != '..') { $path = $source . '/' . $file; if(is_file($path)) { if(!is_file($dest . '/' . $file || $over)) if(!@copy($path, $dest . '/' . $file)) { echo "('.$path.') Ошибка!!! "; } } elseif(is_dir($path)) { if(!is_dir($dest . '/' . $file)) mkdir($dest . '/' . $file); copydirect($path, $dest . '/' . $file, $over); } } } closedir($handle); } } 

      Example: copydirect("D:\papka1", "D:\papka2", 1);

      • Give an example of using the function - shol
      • $ dest what is it? - shol September
      • @ghost rider, why not change the files already in dest ? - avp
      • corrected code - ghost rider
      • copydirect ("D: \ papka1", "D: \ papka2", 1); ---- Copies everything from D: \ papka1 to D: \ papka2, but it is necessary that the D: \ papka1 folder itself with its contents be copied to D: \ papka2 - shol