php复制文件到所有文件夹

时间:2013-01-08 11:55:56

标签: php directory

您好我想将文件复制到目录中的所有文件夹

我的根文件夹树是

我想将根文件夹中的文件复制到每个目标文件夹

文件夹结构

enter image description here

1 个答案:

答案 0 :(得分:1)

由于你有一个静态的文件夹结构,我建议只将不同的子文件夹存储在一个数组中,然后将其循环到copy文件

$rootpath = ".";
$destpaths = array("/Folder1/Subfolder1/AnotherSubFolder/Target/",
               "/Folder2/Subfolder1/AnotherSubFolder/Target/",
               "/Folder3/Subfolder1/AnotherSubFolder/Target/",
               "/Folder4/Subfolder1/AnotherSubFolder/Target/",
               "/Folder5/Subfolder1/AnotherSubFolder/Target/",
               "/Folder6/Subfolder1/AnotherSubFolder/Target/",
               "/FolderN/Subfolder1/AnotherSubFolder/Target/");
$file = '/example.txt';
$copyfrom = $rootpath . $file;

foreach($destpaths as $destpath)
{
    $copyto = $rootpath . $destpath . $file;
    if (!copy($copyfrom, $copyto)) {
        echo "failed to copy $file";
    }
}

正如Aaron W.建议 并使用glob-php来获取递归路径(folder1,folder2 ......) 我将此代码和文件放在同一文件夹中并将其放在与folder1,folder2相同的根路径中...

$rootpath = "..";
$frompath = ".";
$file = '/example.txt';
$tosubpath="/Subfolder1/AnotherSubFolder/Target/";
$copyfrom = $frompath . $file;

listdirs($rootpath,$copyfrom,$tosubpath,$file);


    function listdirs($dir,$copyfrom,$tosubpath,$file) {
        $dirs = glob($dir . '/*', GLOB_ONLYDIR);

    foreach($dirs as $destpath)
    {   

        $copyto = $destpath. $tosubpath . $file;
        if (!copy($copyfrom, $copyto)) {
            echo "failed to copy ".$copyfrom." to".$copyto."<br>";
        }else{
            echo $copyfrom." copied to".$copyto."<br>";
        }
    }
}