Tutorial: How to Create a Zip File with PHP / MySQL

May 13, 2010 by: Anthony Damasco

Recently I added a function to a CMS that I have been evolving to meet the needs of ereads.com. I needed to allow users to select items (in this case ebooks) from the system and then export files that are attached to the books. So lets get started!

What is a Zip File?

“Zip files (.zip or .zipx) are single files, sometimes called “archives”, that contain one or more compressed files. Zip files make it easy to keep related files together and make transporting, e-mailing, downloading and storing data and software faster and more efficient. The Zip format is the most popular compression format used in the Windows environment, and WinZip is the most popular compression utility. ” – winzip.com



What you need to know:
Arrays, MySQL, FTP file permissions

First:

First you need to set up the tables. This is a simplified way of how to do it:

Table Name: Books

id title author description filename
1 The great book TA baron Sr. blah blah blah greatbook.pdf
2 The greater book TA baron Jr. blah blah blah greaterbook.pdf
3 The greatest book TA baron III blah blah blah greatestbook.pdf

Table Name: Book_Cart

id bookid username
1 2 anthony
2 3 anthony

Lets assume:

- that you have all the zip files in a folder called “files”.
- that you already have a way for users to add books to the cart.
- that you have a the username of the person creating the zip stored in a session variable

Second:

You need to setup a folder for the zip file to be created. Make sure that the permissions are set to 777 on that folder. in this example we will pretend the zip folder is called “zips”.

Third:

Here is the zip function:

function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

//close the zip -- done!
$zip->close();

//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}

You can place this code at the top of the folder or you can stick it inside your functions include file. Now we need to run some queries to add the requested files into a zip. In the following example the function above with be included as “zip_function.php”.

include "zip_function.php";
include "database_connect_file.php";

$username = $_SESSION['username'];
$locationFilename = "zips/Book_export.zip";

$get_all = "SELECT * FROM Book_Cart WHERE username='$username'";
$rstall = mysql_query($get_all);
$export_num = mysql_num_rows($rstall);
while ($r1 = mysql_fetch_assoc($rstall)) {
$bookid = $r1['bookid'];

$qry4 = "SELECT * FROM Books WHERE id LIKE '$bookid'";
$result4 = mysql_query($qry4);

while ($row4 = mysql_fetch_assoc($result4)) {
$filename = $row4['filename'];
$files[]= "files/$filename";
}
}

create_zip($files, $locationFilename, true);
echo '<a href="'.$locationFilename.'"> Click here to download PDFs </a><br><br>';

And that should do it. All the code I provided works on mediatemple.net webservers with PHP safe- mode turned off. I found that some other servers don’t allow the creation of zip files. However if the server is set up for it, this should work.

If you have any questions, post them in comments and I will do my best to answer them.

-AD


Comments

24 Responses to “Tutorial: How to Create a Zip File with PHP / MySQL”
  1. Yamaha Lover says:

    Great detailed information, I just bookmarked you on my google reader.

    Sent from my Android phone

  2. Ricky says:

    Now I know who the brainy one is, I’ll keep lonoikg for your posts.

  3. Claudia says:

    Hello Anthony,

    I like you zip picture. Do you allow me to use it for a company internal communication on .zip files?
    Kind regards
    Claudia

  4. phpcours says:

    This article is not saying PHP is the best thing in the world, it is just saying most of the negative opinions are no longer relevant. I know several Ruby developers – some who give talks at the conferences you probably go to – and they are incredibly smart people. That said, they switched away from PHP around version 4 and some of them dont even know about autoloading of __call(). They’re complaining about things being missing that have been in the core for 5 years.

    There are people going around giving strong opinions against PHP who actually don’t know all that much about it and I see this happen all the time. We’re all prone to it. How many of you like ASP.NET? Had a chat with somebody who uses it? They’ll probably tell you things got a lot better since version X.

    Side note: for the love of god, can everyone stop saying “fuck it, use Rails!”. I love Rails, its really good; shiny syntax, great gems, we’ve got it: Rails is good! Now go and tell your boss he’s doing it wrong. Then go and tell all of your clients to switch servers and fire their development team. Not really an option is it.

  5. hi , can anyone tell me how to do this, i m trying to do but cant do, basically i m begginer in php so wana learn new things, plz help me to guide thsi tutorials

  6. kumar says:

    you are giving wonderful information …..thanks a lot…

  7. kumar says:

    you go to w3schools.com and study…this website is for beginners only

  8. Anonymous says:

    I agree this coad

  9. Basti says:

    to avoid the problem with // entries in the archive,
    change and add the following code:

    function create_zip($files = array(),$destination = ”,$overwrite = false,$useFolderStruct = false)

    //add the files
    foreach($valid_files as $file)
    {
    // should we use original folder struct?
    if (!$useFolderStruct)
    $filename = basename($file);
    else if (substr($file,0,1) == ‘/’)
    $filename = substr($file, 1);
    else
    $filename = $file;

    echo “$filename”;

    $zip->addFile($file, $filename);
    }

  10. Basti says:

    ups dont forget to comment out the echo ;)

  11. OllyZeum says:

    great good lesson …

  12. John says:

    i agreee with this, but there was some problem at first than i worked alot on that than it became goooood… :)

  13. الانتشار اللبناني ,بـــحـبك يـا لـــبـــنــان, لبنان الحرية, مغتربين لبنان, عظماء الفن اللبناني, منتديات لبنان, الحياة الزوجية, جمال المراة, اخبار المغترب, الاخبار, الفضائح الفنية, صور فنانات, لتطوير المواقع والمنتديات,الـريـاضــة, تعارف, فنانات, اعلانات

Leave a Reply