0

Is there a Zend Framework method to save content from 3 files (be they dynamically generated or actually exist) and force download as a file?

Similar to this question (which didn't work for me when running from inside a controller so far, despite trying a few different ways):

PHP Zip 3 small text files and force download

Community
  • 1
  • 1
joedevon
  • 2,649
  • 4
  • 28
  • 43

2 Answers2

3

You can use the PHP ZIP library (you need to have that preinstalled) like that:

$zip = new ZipArchive();
if($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true){
    throw new Exception('Could not create zip file ' . $filename);
    die('zip fail');
}else{
    $zip->addFile($file1Uri, 'file1.txt');
    $zip->addFile($file2Uri, 'file2.txt');
}

$zip->close();

if(file_exists($filename)){
    return true;            
}else{
    throw new Exception('Could not create zip file ' . $filename);
}

Deliver the ZIP file:

protected function _deliver($file, $name, $extension, $size, $mime){
    header('Pragma: private');
    header("Expires: -1");
    header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT'); 
    header("Cache-Control: no-cache");
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: " . $mime);
    header("Content-Description: File Transfer"); 
    header('Content-Disposition: attachment; filename="' . $name . '.' . $extension . '"');
    header("Content-Length: " . $size);
    set_time_limit(0);        
    if(!readfile($file)){
        return false;
    }
}
Alex Rashkov
  • 9,833
  • 3
  • 32
  • 58
2

The answer is the upvoted one on your other question. Do it from controller, then call exit after you output the zip data so don't you render the view.

Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168
  • I'm getting this error on addFile or addFromString (I've tried both): "Invalid or unitialized Zip object" even though if I do a file_get_contents and echo it out, the data is valid. – joedevon Feb 05 '10 at 00:46
  • You have to call $zip->open($filename). with a unique filename (maybe the sessionID of theuser). You can't create a zip in memory. – Byron Whitlock Feb 05 '10 at 00:54
  • Ah, that makes sense. So basically the upvoted answer is wrong? It doesn't have a $zip->open($file) & in the comments says "it just keeps it in memory before echoing it." – joedevon Feb 05 '10 at 04:08
  • Yes, it is frustrating but i came across the same issue before. It is probably dependent on the php version. – Byron Whitlock Feb 05 '10 at 18:41
  • And maybe windows vs *nix. I'd like it to work in both envs. Going to test it presently. – joedevon Feb 05 '10 at 19:43
  • That wasn't it. There was a bunch of stuff, I kept throwing different settings, headers, etc and finally got it to work. Whew! Thanks for your help-. – joedevon Feb 05 '10 at 22:24