In PHP I want to recursively copy all the files from a directory and it's sub-directories to a single directory with no sub-directories .
eg
.../dir/subdir1/file1.pdf
.../dir/subdir1/file2.pdf
.../dir/subdir2/file3.pdf
.../dir/subdir2/file4.pdf
should become:
.../newdir/file1.pdf
.../newdir/file2.pdf
.../newdir/file3.pdf
.../newdir/file4.pdf
ie. there is no 'subdir' level anymore.
I am using this PHP code, it copies all the files but it is retaining the subdirectories which is not desired:
<?php
$src = "/dir/";
$dst = "/newdir/";
function recurse_copy($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
recurse_copy($src,$dst);
echo "<H3>Copy Paste completed!</H3>"; //output when done
?>
You are passing a wrong value for the destination argument when the file is a directory. If you want a flat directory structure, it should be just:
recurse_copy($src . '/' . $file, $dst);
instead of:
recurse_copy($src . '/' . $file, $dst . '/' . $file);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.