Download multiple files as a zip-file using php

后端 未结 4 1497
醉梦人生
醉梦人生 2020-11-22 16:16

How can I download multiple files as a zip-file using php?

相关标签:
4条回答
  • 2020-11-22 16:36

    Create a zip file, then download the file, by setting the header, read the zip contents and output the file.

    http://www.php.net/manual/en/function.ziparchive-addfile.php

    http://php.net/manual/en/function.header.php

    0 讨论(0)
  • 2020-11-22 16:40

    You are ready to do with php zip lib, and can use zend zip lib too,

    <?PHP
    // create object
    $zip = new ZipArchive();   
    
    // open archive 
    if ($zip->open('app-0.09.zip') !== TRUE) {
        die ("Could not open archive");
    }
    
    // get number of files in archive
    $numFiles = $zip->numFiles;
    
    // iterate over file list
    // print details of each file
    for ($x=0; $x<$numFiles; $x++) {
        $file = $zip->statIndex($x);
        printf("%s (%d bytes)", $file['name'], $file['size']);
        print "
    ";    
    }
    
    // close archive
    $zip->close();
    ?>
    

    http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/

    and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php

    0 讨论(0)
  • 2020-11-22 16:43

    You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

    $files = array('readme.txt', 'test.html', 'image.gif');
    $zipname = 'file.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);
    foreach ($files as $file) {
      $zip->addFile($file);
    }
    $zip->close();
    

    and to stream it:

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipname);
    header('Content-Length: ' . filesize($zipname));
    readfile($zipname);
    

    The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.

    0 讨论(0)
  • 2020-11-22 16:47

    This is a working example of making ZIPs in PHP:

    $zip = new ZipArchive();
    $zip_name = time().".zip"; // Zip name
    $zip->open($zip_name,  ZipArchive::CREATE);
    foreach ($files as $file) {
      echo $path = "uploadpdf/".$file;
      if(file_exists($path)){
      $zip->addFromString(basename($path),  file_get_contents($path));  
      }
      else{
       echo"file does not exist";
      }
    }
    $zip->close();
    
    0 讨论(0)
提交回复
热议问题