Getting corrupted or empty zip by ZipArchive php

Durgesh Suthar picture Durgesh Suthar · Feb 9, 2013 · Viewed 11.7k times · Source

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

Answer

nice ass picture nice ass · Feb 9, 2013

Try getting the full file path and name just before $zip->close();

$filename = $zip->filename;

And use that instead of $zipname when reading the file and getting the file size