Php 如何将此脚本更改为压缩dir数组?

Php 如何将此脚本更改为压缩dir数组?,php,directory,zip,archive,Php,Directory,Zip,Archive,我对SO和PHP都是新手。我在网上找到了一个压缩目录的脚本,并对其进行了编辑,以便它将压缩文件发送到浏览器进行下载,然后从服务器上删除该文件 它工作得很好,但是我想压缩多个目录,而不是一个 我需要如何修改脚本才能完成这一任务 $date = date('Y-m-d'); $dirToBackup = "content"; $dest = "backups/"; // make sure this directory exists! $filename = "backup-$date.zip";

我对SO和PHP都是新手。我在网上找到了一个压缩目录的脚本,并对其进行了编辑,以便它将压缩文件发送到浏览器进行下载,然后从服务器上删除该文件

它工作得很好,但是我想压缩多个目录,而不是一个

我需要如何修改脚本才能完成这一任务

$date = date('Y-m-d');

$dirToBackup = "content";
$dest = "backups/"; // make sure this directory exists!
$filename = "backup-$date.zip";

$archive = $dest.$filename;


function folderToZip($folder, &$zipFile, $subfolder = null) {
    if ($zipFile == null) {
        // no resource given, exit
        return false;
    }
    // we check if $folder has a slash at its end, if not, we append one
    $folder .= end(str_split($folder)) == "/" ? "" : "/";
    $subfolder .= end(str_split($subfolder)) == "/" ? "" : "/";
    // we start by going through all files in $folder
    $handle = opendir($folder);
    while ($f = readdir($handle)) {
        if ($f != "." && $f != "..") {
            if (is_file($folder . $f)) {
                // if we find a file, store it
                // if we have a subfolder, store it there
                if ($subfolder != null)
                    $zipFile->addFile($folder . $f, $subfolder . $f);
                else
                    $zipFile->addFile($folder . $f);
            } elseif (is_dir($folder . $f)) {
                // if we find a folder, create a folder in the zip 
                $zipFile->addEmptyDir($f);
                // and call the function again
                folderToZip($folder . $f, $zipFile, $f);
            }
        }
    }
}

// create the zip
$z = new ZipArchive();
$z->open($archive, ZIPARCHIVE::CREATE);
folderToZip($dirToBackup, $z);
$z->close();

// download the zip file
$file_name = basename($archive);

header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($archive));

readfile($archive);

// delete the file from the server
unlink($archive);
exit;
谢谢你的帮助

Irma将$dirToBackup设置为

$dirToBackup = array("restricted","ci");
然后:

foreach($dirToBackup as $d){
    folderToZip($d, $z, $d);
}
就这些。
问候,

非常感谢,这很有帮助。所有文件和文件夹都打包到一个zip文件中。但是如果我压缩“folder1”和“folder2”,我怎么会在压缩文件中得到这样的文件结构:
zipfile:-folder1-folder2
我通过将第三个参数传递给folderToZip函数来更正答案。