Sep 9, 2011

How to make Zip archives with PHP - part 1

Actually working with zip archives isn’t that obvious that it looks from the documentation. But if you want an adventure try to make tar or tar.gz. Actually in one of my next posts I will describe the procedure. Now, we are talking about zip here.

Example: Create archive and add file to it
<?php
 // the file that we want to compress
 $file = "path/filetocompress.txt";

 
 // how we want to name the file in the archive
 $name = "filename.txt";
 
 // we need to create new object
 $zip = new ZipArchive();

 
 // we are using ZipArchive::open with flag CREATE to make new zip archive
 if ($zip->open("ournew.zip", ZipArchive::CREATE) === TRUE) {

  
  // here the first parameter is the file on our system
  // the second is the name to be used for this file in our new zip 
     $zip->addFile($file, $name);

     
     // close is used for both close and save
     $zip->close();
 } else {

     echo 'Error';
 }
?>

No comments:

Popular Posts