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);
}
CodePudding user response:
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);
}
CodePudding user response:
recurse_copy('TOCOPY/', 'TEST/', 3);
function recurse_copy($source, $destination, $depth = 0) {
echo "copy $depth from $source to $destination" . PHP_EOL;
if ($depth < 0) {
return;
}
$directory = opendir($source);
if (!$directory) {
return;
}
@mkdir($destination);
while(false !== ($file = readdir($directory))) {
if (in_array($file, ['.', '..'])) {
continue;
}
$currentSourcePath = $source . '/' . $file;
$currentDestinationPath = $destination . '/' . $file;
if (is_dir($currentSourcePath)) {
recurse_copy($currentSourcePath, $currentDestinationPath, $depth - 1);
continue;
}
copy($currentSourcePath, $currentDestinationPath);
}
closedir($directory);
}