【问题标题】:Downloading zip file automatically via php code通过php代码自动下载zip文件
【发布时间】:2018-02-06 11:51:05
【问题描述】:
<body>
    <?php
        $zip = new ZipArchive;

        if ($zip->open(getcwd() .'/read.zip', ZipArchive::CREATE) === TRUE) {
            $zip->addFile(getcwd() . '/read.txt','/newname.txt');
            $zip->close();


            $file = getcwd() . '/read.zip';
             // http headers for zip downloads
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=\"read.zip\"");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".filesize($file));
            readfile($file);

            echo 'ok';

        } else {
            echo 'failed';
        }
    ?>
</body>

我有以下代码,并希望在我们运行此页面时自动下载此代码生成的 zip 文件。

【问题讨论】:

标签: php


【解决方案1】:

您需要为客户端添加有关文件下载的标头。只需查看手册示例:http://php.net/manual/en/function.header.php#example-5315

<?php
    $file = getcwd() . '/read.zip';
    // http headers for zip downloads
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"read.zip\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($file));
    ob_end_flush();
    @readfile($file);

【讨论】:

  • 我已经尝试了上面的代码。但它仍然无法正常工作。我只是一个初学者。你能帮我更多吗?
  • 我在 $zip->close(); 之后添加了这个标题
  • @Jay,对不起!我刚刚错过了主要的事情 - readfile($file);
  • 它生成 o/p 像........ Dok........但仍然没有自动下载 zip
  • 等一下,我本地查一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多