zip and download files using php

前端 未结 7 894
暗喜
暗喜 2021-02-02 03:41

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 eith

7条回答
  •  终归单人心
    2021-02-02 04:00

    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:

    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.

    $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;
       }
    }
    

提交回复
热议问题