简体   繁体   English

使用php下载多个文件作为zip文件

[英]Download multiple files as a zip-file using php

如何使用php将多个文件下载为zip文件?

You can use the ZipArchive class to create a ZIP file and stream it to the client. 您可以使用ZipArchive类创建一个ZIP文件并将其流式传输到客户端。 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. 第二行强制浏览器向用户显示一个下载框,并提示名称filename.zip。 The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified. 第三行是可选的,但某些(主要是较旧的)浏览器在某些情况下会出现问题,而未指定内容大小。

This is a working example of making ZIPs in PHP: 这是在PHP中制作ZIP的有效示例:

$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();

Create a zip file, then download the file, by setting the header, read the zip contents and output the file. 创建一个zip文件,然后通过设置标题下载文件,读取zip内容并输出文件。

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

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

You are ready to do with php zip lib, and can use zend zip lib too, 您已经准备好使用php zip lib,也可以使用zend zip lib,

<?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/ 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 还有这个http://www.php.net/manual/zh/class.ziparchive.php的 php pear lib

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM