4

What is the easiest way of creating 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

2

2 Answers 2

6

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');
Sign up to request clarification or add additional context in comments.

1 Comment

it is little bit different on that page -> if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { exit("cannot open <$filename>\n"); }
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.