复制递归文件和文件夹但跳过父级

时间:2012-11-14 08:08:53

标签: php

function copy_directory( $source, $destination ) {
    if ( is_dir( $source ) ) {
        @mkdir( $destination );
        $directory = dir( $source );
        while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
            if ( $readdirectory == '.' || $readdirectory == '..' ) {
                continue;
            }
            $PathDir = $source . '/' . $readdirectory; 
            if ( is_dir( $PathDir ) ) {
                copy_directory( $PathDir, $destination . '/' . $readdirectory );
                continue;
            }
            copy( $PathDir, $destination . '/' . $readdirectory );
        }

        $directory->close();
    }else {
        copy( $source, $destination );
    }
}

这是我的脚本,用于将整个目录和文件复制到另一个目的地。但我有小问题

我的文件夹就像:

cinch.v2.1.1\cinch\cinch\other folders and files
loopy.v2.1.3\loopy\loopy\other folders and files
musy.v3.1.4\musy\musy\other folders and files
...

我需要复制最后(深度3)cinch,loopy,musy文件夹与子文件夹和文件而不是整个结构。如何更改脚本。

和复制结构应如下所示:

cinch\other folders and files
loopy\other folders and files
musy\other folders and files

我从

开始
if (strpos($readdirectory, '.') === false && strpos($readdirectory, '_') === false) {   

但这不起作用。

1 个答案:

答案 0 :(得分:1)

您必须首先查找3级目录,然后将这些目录复制到目的地:

function copy_directory(...) {
...
}

function copy_depth_dirs($source, $destination $level)
{
    $dir = dir($source);
    while (($entry = $dir->read()) !== FALSE) {
        if ($entry != '.' && $entry != '..' && is_dir($entry)) {
            if ($level == 0) {
                copy_directory($source . '/' . $entry, $destination);
            } else {
                copy_depth_dirs($source . '/' . $entry, $destination, $level - 1);
            }
        }
    }
}

copy_depth_dirs('cinch.v2.1.1', $destination, 3);
相关问题