Search code examples
phpphp-ziparchive

PHP ZipArchive not saving


I'm creating a PHP automatic downloader for zipped images. However, the downloaded ZIP is empty! Hopefully somebody will know the issue- it's bound to be simple.

Many thanks, Nick.

PHP

    foreach($_SESSION["photoBasket"] as $id){
       $files[] = array(
               "loc" => "../photos/$id.png",
               "name" => "$id.png"
                );
    }

    $zipname = tempnam(sys_get_temp_dir(), 'zip');
        $zip = new ZipArchive();
        $zip->open($zipname, ZipArchive::CREATE);
        foreach ($files as $file) {
          $zip->addFile($file["loc"],$file["name"]);
          //$zip->addFromString($file["name"],"something here"); WORKS FINE
        }
        $zip->close();

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename=test.zip');
    readfile($zipname);
    unlink($zipname);

Solution

  • You must create your file in a writeable folder; also, your filename should be unique so that two people downloading a ZIP at the same time don't overwrite each other. Let PHP work out the specifics of that, using tempnam() and sys_get_temp_dir(). And don't forget to remove the temporary file after you've sent it down the wire!

    $zipname = tempnam(sys_get_temp_dir(), 'zip');
    ...
    unlink($zipname);