使用 php 压缩和下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20162360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:56:02  来源:igfitidea点击:

zip and download files using php

phpzip

提问by Phani

I am trying to zip and download files from a folder named "upload". Zip file is downloading but I couldn't open (extract) it. I am getting an error like "The archive is either in unknown format or damaged".

我正在尝试从名为“上传”的文件夹中压缩和下载文件。正在下载 Zip 文件,但我无法打开(提取)它。我收到类似“存档格式未知或已损坏”的错误消息。

I have found the following code to zip the folder.

我找到了以下代码来压缩文件夹。

<?php
    $files = "upload/".array('Dear GP.docx','ecommerce.doc');
    $zipname = 'filename.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);
    foreach ($files as $file) {
      $zip->addFile($file);
    }
    $zip->close();
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename=filename.zip');
    header('Content-Length: ' . filesize($zipfilename));
    readfile($zipname);
?>

回答by Phani

Thanks for your answers.

感谢您的回答。

<?php
    $files = array('Dear GP.docx','ecommerce.doc');

    # create new zip opbject
    $zip = new ZipArchive();

    # create a temp file & open it
    $tmp_file = tempnam('.','');
    $zip->open($tmp_file, ZipArchive::CREATE);

    # loop through each file
    foreach($files as $file){

        # download file
        $download_file = file_get_contents($file);

        #add it to the zip
        $zip->addFromString(basename($file),$download_file);

    }

    # close zip
    $zip->close();

    # send the file to the browser as a download
    header('Content-disposition: attachment; filename=Resumes.zip');
    header('Content-type: application/zip');
    readfile($tmp_file);
 ?>

回答by Sankar

I had spent more than 6 hours on this downloading zip files on my mac (localhost) - Though the file was getting downloaded, I could not unzip them (getting cpgz files). Apparently, none of the solutions mentioned in stack overflow (around a variety of questions on zip file download) worked. Finally, after trial and error, I found that the following code works:

我在我的 mac(本地主机)上花了 6 个多小时来下载 zip 文件 - 虽然文件正在下载,但我无法解压缩它们(获取 cpgz 文件)。显然,堆栈溢出中提到的所有解决方案(围绕 zip 文件下载的各种问题)都没有奏效。最后,经过反复试验,我发现以下代码有效:

None of the people answered earlier talked about the ob_start() and where exactly you should put it. Anyway, that alone was not the answer - you need to use those three lines above ob_start() too.

之前回答的人都没有谈到 ob_start() 以及您应该把它放在哪里。无论如何,仅此而已不是答案-您也需要使用 ob_start() 上方的那三行。

$file=$zippath.$filename;
if (headers_sent()) {
    echo 'HTTP header already sent';
} else {
    if (!is_file($file)) {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
        echo 'File not found';
    } else if (!is_readable($file)) {
        header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
        echo 'File not readable';
    } else {
        while (ob_get_level()) {
            ob_end_clean();
        }
       ob_start();
       header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
       header("Content-Type: application/zip");
       header("Content-Transfer-Encoding: Binary");
       header("Content-Length: ".filesize($file));
       header('Pragma: no-cache');
       header("Content-Disposition: attachment; filename=\"".basename($file)."\"");
       ob_flush();
       ob_clean();
       readfile($file);
       exit;
   }
}

回答by Fahad

Answer is good but Please add these lines before header. Zip file is open in all zip software (winzip, winrar etc.)

答案很好,但请在标题前添加这些行。Zip 文件在所有 zip 软件(winzip、winrar 等)中打开

if (headers_sent()) 
    {
        // HTTP header has already been sent
        return false;
    }
// clean buffer(s)
while (ob_get_level() > 0)
    {
        ob_end_clean();
    }

回答by M Arfan

 $zip = new ZipArchive;
        if ($zip->open('assets/myzip.zip',  ZipArchive::CREATE)) {
            $zip->addFile('folder/bootstrap.js', 'bootstrap.js');
            $zip->addFile('folder/bootstrap.min.js', 'bootstrap.min.js');
            $zip->close();
            echo 'Archive created!';
            header('Content-disposition: attachment; filename=files.zip');
            header('Content-type: application/zip');
            readfile($tmp_file);
       } else {
           echo 'Failed!';
       }

I got this code to download files from a folder.

我得到了这个代码来从一个文件夹下载文件。

回答by Kevin G Flynn

Please use below code instead of $zip->addFile($file);

请使用下面的代码而不是$zip->addFile($file);

<?php
$zip->addFile($file_path, $filename);
?>

回答by Aydin Hassan

$files = "upload/".array('Dear GP.docx','ecommerce.doc');

Should be:

应该:

$files = array('upload/Dear GP.docx','upload/ecommerce.doc');

If you are still having issues then you should check if you have write permission to the current directory. You can check the return value of close()to check whether the file was actually written.

如果您仍然遇到问题,那么您应该检查您是否对当前目录具有写权限。您可以检查的返回值close()来检查文件是否真的被写入。

$res = $zip->close();
var_dump($res);

The output should be bool(true)if the write was successful.

输出应该是bool(true)写入成功。

Looks like you have a the wrong var name in the filesize()call also:

看起来您在filesize()调用中也有错误的 var 名称:

header('Content-Length: ' . filesize($zipfilename));

Should probably be:

应该是:

header('Content-Length: ' . filesize($zipname));

You could also add extra validation to check whether the files you are adding to the zip actually exist and before sending check the zip file exists.

您还可以添加额外的验证来检查您添加到 zip 的文件是否实际存在,并在发送之前检查 zip 文件是否存在。

Edit: Turn on display errors to help you debug locally:

编辑:打开显示错误以帮助您在本地调试:

ini_set('display_errors', 1);
error_reporting(E_ALL);