I want to copy a whole folders/files tree from one location to another, but for a particular depth I want to perform a transliteration of the destination folder from one language to another.
So for /src/depth1/depth2/depth3/depth4/file
I want to transliterate all depth3 folders to another language before copying them over to the destination path.
So I found this little, robust recursive function, which should help me in my task, and then I tried to add a depth control feature so that the transliteration replacement takes place only on depth3
folders. But at first, what I did only added to the depth. Then I thought I found the correct place to add the $depth--;
, but unfortunately I can’t figure out where to subtract from it in order to start over a new branch…
Could someone help figure this out please?
recurse_copy('TOCOPY/', 'TEST/'); function recurse_copy($src,$dst,$depth = 0) { echo $src . ' ' . $depth.'<br>'; $dir = opendir($src); @mkdir($dst); while(false !== ( $file = readdir($dir)) ) { $depth++; if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) { recurse_copy($src . '/' . $file,$dst . '/' . $file, $depth); } else { $depth--; // copy($src . '/' . $file,$dst . '/' . $file); //I commented this line to save time from copying files again and again while I'm experimenting with the depth control... } } } closedir($dir); }
Advertisement
Answer
Not tested, but if my understanding is right this should work, plus minus 1 depth.
recurse_copy('TOCOPY/', 'TEST/', 3); function recurse_copy($src, $dst, $depth = 0) { echo $src . ' ' . $depth . '<br>'; if ($depth <= 0) { return; } $dir = opendir($src); @mkdir($dst); while(false !== ( $file = readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) { recurse_copy($src . '/' . $file,$dst . '/' . $file, $depth - 1); } else { // copy($src . '/' . $file,$dst . '/' . $file); //I commented this line to save time from copying files again and again while I'm experimenting with the depth control... } } } closedir($dir); }
Addition: This version will rename some directories according to their depth.
recurse_copy_special('TOCOPY/', 'TEST/'); function recurse_copy_special($src, $dst, $depth = 0) { echo $src . ' ' . $depth . '<br>'; $base = basename($dst); $dir = dirname($dst); if ($depth == 1) { $dst = $dir . '/' . 'changed1-' . $base; } if ($depth == 2) { $dst = $dir . '/' . 'changed2-' . $base; } if ($depth == 3) { $dst = $dir . '/' . 'changed3-' . $base; } $dir = opendir($src); if (!file_exists($dst)) { mkdir($dst); } while (false !== ($file = readdir($dir))) { if (($file != '.') && ($file != '..')) { if (is_dir($src . '/' . $file)) { recurse_copy_special($src . '/' . $file, $dst . '/' . $file, $depth + 1); } else { copy($src . '/' . $file, $dst . '/' . $file); } } } closedir($dir); }