Spiga

How to Create a zip file with php on the fly

by Gabi Solomon

For a future project I needed these days some easy to use zip or gzip class to create a zip file from files / folders inside a specified directory. A short search on Google has lead me to the Create ZIP File PHP class from Rochak Chauhan.

This class can create ZIP archives from lists of files.

The class provides means to add individual files or whole directories to the list of files packed into a ZIP archive.

The class can generate the packed archive as a string value.

The class can also output the necessary request response headers to serve the generated ZIP archive for download.

The supplied example demonstrates how to use the class to store the ZIP archive in a file, serve it for download and delete the file after it is served.

Example of usage

PHP:
  1. <?php
  2.  
  3. include_once("createZip.inc.php");
  4. $createZip = new createZip; 
  5.  
  6. $createZip -> addDirectory("dir/");
  7.  
  8. $fileContents = file_get_contents("img.jpg")
  9. $createZip -> addFile($fileContents, "dir/img.jpg")
  10.  
  11.  
  12. $fileName = "archive.zip";
  13. $fd = fopen ($fileName, "wb");
  14. $out = fwrite ($fd, $createZip -> getZippedfile());
  15. fclose ($fd);
  16.  
  17. $createZip -> forceDownload($fileName);
  18. @unlink($fileName);
  19. ?>

Related Posts

  • hello,
    i used the same flow for creating zip file that contains some files. but when extracting those, with winrar no error occurs. but with winzip the error comes is

    error [C:\Documents and Settings\Amit\Desktop\recharge.zip]: start of central directory not found; Zip file corrupt.
    Possible cause: file transfer error
  • @amit shah
    I dont know what to tell you .. i used it and it worked for me.
  • GABI:

    do u get any error while extracting it with winzip?
  • no it worked on the files i tested
  • if u can try to see what happens when u add mutiple file in a zip folder.
  • Tripp
    I tried this out and it works great with winzip. However, one of my buddy's can't open the zip archive on his Mac. Any ideas?
  • @tripp
    i think there might be an incompatibility with the mac, havent tested it out.
  • it's working now. i just added
    ob_end_clean();
    before echo the zip file content.
  • Unfortunately like a lot of the PHP Zip classes this one doesn't unarchive on mac.

    For Mac friendly version you can try this one!

    http://thewebdevelopmentblog.com/2009/08/script...
  • Fred Bloggs
    ob_end_clean();

    Worked a treat, files zipped ok without including directories but as soon as I added one I got the same problem as amit shah. 2 days of searching google and you have the solution, nice one amit shah.
blog comments powered by Disqus