开发者

Dynamically creating zip with php

开发者 https://www.devze.com 2022-12-21 11:30 出处:网络
What is the easiest way of creat开发者_如何学Cing dynamically zip files with php? For example, I have these files on the server,

What is the easiest way of creat开发者_如何学Cing dynamically zip files with php?

For example,

I have these files on the server,

Root -> Folder 1 -> file1.wav
Root -> Folder 2 -> file2.jpg 

I want to create a zip file contains these 2 files and allow user to download it.

any help ?

Thx in advance


See the ZipArchive class; it has what you need.

http://www.php.net/manual/en/class.ziparchive.php

Example from PHP.Net:

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->addFile('/path/to/index.txt', 'newname.txt');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

After zipping it, you can output a mime-type header and output the file:

header('Content-type: application/zip');
readfile('test.zip');


this is the working example of making zip 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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号