How to ZIP a folder on the fly using php

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to ZIP a folder on the fly using php

Post by Neo » Mon Jul 11, 2011 7:07 pm

I know there are several ways to do this. But this is the easiest I found.

Code: Select all

<?php
     //Get the directory to zip
     $filename_no_ext= $_GET['directtozip'];

     // we deliver a zip file
     header("Content-Type: archive/zip");

     // filename for the browser to save the zip file
     header("Content-Disposition: attachment; filename=$filename_no_ext".".zip");

     // get a tmp name for the .zip
     $tmp_zip = tempnam ("tmp", "tempname") . ".zip";

     //change directory so the zip file doesnt have a tree structure in it.
     chdir('user_uploads/'.$_GET['directtozip']);
     
     // zip the stuff (dir and all in there) into the tmp_zip file
     exec('zip '.$tmp_zip.' *');
     
     // calc the length of the zip. it is needed for the progress bar of the browser
     $filesize = filesize($tmp_zip);
     header("Content-Length: $filesize");

     // deliver the zip file
     $fp = fopen("$tmp_zip","r");
     echo fpassthru($fp);

     // clean up the tmp zip file
     unlink($tmp_zip);
?>
Save this code as zip_folders.php

Then when you want to provide a link to download a users uploads as a zip file, you link to it like,

Code: Select all

<a href="zip_folders.php?directtozip=THE USERS DIRECTORY">Download All As Zip</a> 
That will cause a download prompt to appear for the user when clicking on the link.
Post Reply

Return to “PHP & MySQL”