Monday, March 7, 2011

Create zip file on the fly with PHP

Hi,

This post is about creating zip files on the fly. I have found a class over the internet which allows you to do that. First of all you need to download the class file. Click here to download the class file. Once you have downloaded the code, create another file example.php and put the following:


<?php
require "zip.class.php";
$zipfile = new zipfile;

function make_archieve($location,$type,$filename,$zipfile)
{
if($type=="dir"){
$dir=opendir($location);
$i=0;
while($files=readdir($dir)){
if($i>1 && filetype($location."/".$files)!="dir"){
$tmp_location=str_replace("./","",$location);
$tmp_location=$tmp_location."/";
if($tmp_location=="./"){$tmp_location="";}
$zipfile->create_file(file_get_contents($location."/".$files), $tmp_location.$files);


}elseif($i>1){
$tmp_location=str_replace("./","",$location);
$tmp_location= str_replace("./","",$tmp_location."/".$files);
$zipfile->create_dir($tmp_location);
make_archieve($location."/".$files,$type,$filename,$zipfile);
}
$i++;
}
header("Content-type: application/zip");
header("Content-disposition: attachment;filename=\"".$filename."\"");
echo $zipfile->zipped_file();
}else{

}
}

make_archieve(".","dir","archieve.zip",$zipfile);

?>

In the above code I have created a recursive function to browse through all the files and subfolders of a given directory and creating a zip file for it. As the zip file is getting created it is also getting downloaded at the same time. So you do not have to worry about storing the zip file in the server. This kind of functionality is important in music websites where an entire album needs to be zipped and downloaded.

The above code is pretty much self explanatory. But if you still find any issues, post in your comments and I will get back as soon I can :)

Best of luck




5 comments:

  1. How do I set the directory that I want to zip download, for example : $directory="/www/mywebsite/';

    Chris

    ReplyDelete
  2. Try using this:
    make_archieve("/www/mywebsite/","dir","my_zip.zip",$zipfile);

    make sure the directory /www/mywebsite/ has appropriate permissions, to read and write.

    ReplyDelete
  3. Hi. It is still trying to download the contents of my entire server haha. I have used the code above and amended it appropriately. It stops after zipping 528.2mb and when I try to unpack the file it says the .zip file is corrupt.

    ReplyDelete