PHP ZIP files on the fly

前端 未结 7 1774
有刺的猬
有刺的猬 2020-12-02 17:06

What\'s the easiest way to zip, say 2 files, from a folder on the server and force download? Without saving the \"zip\" to the server.

    $zip = new ZipArc         


        
7条回答
  •  爱一瞬间的悲伤
    2020-12-02 17:30

    Unfortunately w/ PHP 5.3.4-dev and Zend Engine v2.3.0 on CentOS 5.x I couldn't get the code above to work. An "Invalid or unitialized Zip object" error message was all I could get. So, in order to make it work, I had to use following snippet (taken from the example by Jonathan Baltazar on PHP.net manual, at the ZipArchive::open page):

    // Prepare File
    $file = tempnam("tmp", "zip");
    $zip = new ZipArchive();
    $zip->open($file, ZipArchive::OVERWRITE);
    
    // Stuff with content
    $zip->addFromString('file_name_within_archive.ext', $your_string_data);
    $zip->addFile('file_on_server.ext', 'second_file_name_within_archive.ext');
    
    // Close and send to users
    $zip->close();
    header('Content-Type: application/zip');
    header('Content-Length: ' . filesize($file));
    header('Content-Disposition: attachment; filename="file.zip"');
    readfile($file);
    unlink($file); 
    

    I know this is different than working w/ memory only - unless you have your tmp area in ram ;-) - but maybe this can help out someone else, who's struggling with the solution above, like I was; and for which performance penalty is not an issue.

提交回复
热议问题