简体   繁体   中英

Downloading zip file automatically via php code

<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>

I have following code and want to download zip file automatically that is being produced by this code when we run this page.

u need to add header for the client about file downloading. just see the manual example: 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM