Zip Stream in PHP

后端 未结 5 1322
轮回少年
轮回少年 2020-11-30 11:28

I have a PHP script that creates a zip file on the fly and forces the browser to download the zip file. The question is: could I directly write the zip file to an output str

相关标签:
5条回答
  • 2020-11-30 11:33

    This library seems to be what you're looking for: https://github.com/maennchen/ZipStream-PHP

    0 讨论(0)
  • 2020-11-30 11:34

    No, you have to use a temporary file, as in here.

    0 讨论(0)
  • 2020-11-30 11:38

    If you're using the zip extension, the answer seems to be "no." The close method in the ZipArchive class is what triggers a write, and it seems to want to write to a file. You might have some luck using Streams to simulate a file, but then you're keeping the entire thing in memory, and you still couldn't send it until you're done adding files.

    If you're having problems with timeouts or other problems while having a user wait for the zip file to be created, try a multi-step download process:

    1. User picks whatever they pick to create the zip
    2. They're taken to a status page that uses ajax calls to actually build the zip file in the background. A pretty, distracting animation should keep their attention.
    3. After the background processes build the zip, the user is redirected to a script that performs the download / redirected to the file.
    0 讨论(0)
  • 2020-11-30 11:40

    If your web server is running linux, then you CAN do it streaming without a temp file being generated. Under win32 you may need to use Cygwin or something similar.

    If you use "-" as the zip file name, it will compress to stdout. From there, it's easy enough to redirect that stream using popen(). The "-q" argument simply tells zip to not output the status text it normally would. See the zip(1) manpage for more info.

    <?
         $zipfilename = "zip_file_name.zip";
    
         if( isset( $files ) ) unset( $files );
    
         $target = "/some/directory/of/files/you/want/to/zip";
    
         $d = dir( $target );
    
         while( false !== ( $entry = $d->read() ) )
         {
           if( substr( $entry, 0, 1 ) != "." && !is_dir( $entry ) ) 
           {
             $files[] = $entry;
           }
         }
    
         header( "Content-Type: application/x-zip" );
         header( "Content-Disposition: attachment; filename=\"$zipfilename\"" );
    
         $filespec = "";
    
         foreach( $files as $entry )
         {
           $filespec .= "\"$entry\" ";
         }
    
         chdir( $target );
    
         $stream = popen( "/usr/bin/zip -q - $filespec", "r" );
    
         if( $stream )
         {
           fpassthru( $stream );
           fclose( $stream );
         }
    ?>
    
    0 讨论(0)
  • 2020-11-30 11:44

    Yes, you can directly stream the zip to the client using this git rep: Zip Stream Large Files

    0 讨论(0)
提交回复
热议问题