通过php代码自动下载zip文件

时间:2018-02-06 11:51:05

标签: php

<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文件。

1 个答案:

答案 0 :(得分:0)

你需要为客户端添加关于文件下载的标题。请参阅手册示例: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);