【问题标题】:How to change this script to zip an array of dirs?如何更改此脚本以压缩目录数组?
【发布时间】:2013-03-04 11:31:20
【问题描述】:

我是 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;

感谢您的帮助!

厄玛

【问题讨论】:

    标签: php directory zip archive


    【解决方案1】:

    将 $dirToBackup 设置为

    $dirToBackup = array("restricted","ci");
    

    然后:

    foreach($dirToBackup as $d){
        folderToZip($d, $z, $d);
    }
    

    仅此而已。 问候,

    【讨论】:

    • 非常感谢,这很有帮助。所有文件和文件夹都打包到一个 zip 文件中。但是如果我压缩“folder1”和“folder2”,我怎么会在 zip 中得到这样的文件结构:zipfile: - folder1 - folder2
    • 我通过将第三个参数传递给 folderToZip 函数更正了答案。
    猜你喜欢
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多