zip and download files using php

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);
 ?>

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

Tags:

Php

Zip