phpzipphp-ziparchive

Getting corrupted or empty zip by ZipArchive php


I am getting zip file downloaded by following code without any error but the downloaded zip file is empty or corrupted and size is always about 200 Bytes. i.e. I cannot open that zip file. Also ZipArchive::getStatusString() is also showing "No error"

code is :

public function getzip(){
    global $config;
    $files=array();
    if(isset($_COOKIE['hashes'])){
        $hashes=explode(',',$_COOKIE['hashes']);
        for ($i=0; $i <count($hashes); $i++) {
            array_push($files,$config["domain"]."/download/".$hashes[$i]); 
        }
    }
    if(count($files)){
        $zipname='basket.zip';
        $zip = new ZipArchive;
        $zip->open($zipname,ZipArchive::CREATE);
        foreach ($files as $key=>$value ) {
            $zip->addFile($value);
        }
        $status=$zip->getStatusString();
        $zip->close();

    if(!$zipname)
    {
        echo "Nothing in Basket";
    }
    else
    {   header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-Disposition:attachment; filename='.basename($zipname));
        header('Content-Length:'.filesize($zipname));
        readfile($zipname);
    }
}

Solution

  • This is my best guess. What's going wrong here is that in your array $files the values you're storing are probably not actual paths to files.

    Remember: You can't pass URLs into $zip->addfile(), you need your actual files.