tags:

views:

126

answers:

1

I'm working on a site which downloads folders users upload from our other server, but first we have to zip that folder - how do I zip up a whole folders' contents?

+1  A: 

Take a look at the documentation for ZipArchive. If you've got a particular problem with it, edit your question and I'll try to be more helpful. You may not have ZipArchive installed - if not, follow the installation instructions.

Functions that you'll need:

  • open: Opens the zip archive (you'll want to use the flag ZIPARCHIVE::CREATE).
  • addEmptyDir: Creates an empty directory in the zip archive that you can add files to.
  • addFile: Adds a file on your filesystem to the archive. You'll presumably want to run through the folder you wish to add files from calling this function.
  • close: Close the zip archive when you're done writing to it.
  • extractTo: Get the files out of the zip archive to put them somewhere

Sample code:

<?php

$writezip = new ZipArchive;
if ($writezip->open('test.zip') === TRUE) {
    if($zip->addEmptyDir('newDirectory')) {
        $writezip->addFile('/path/to/index.txt', 'newDirectory/newname.txt');
        $writezip->close();
        echo 'ok';
    }
    else {
        echo 'failed to create directory';
    }
}
else {
    echo 'failed';
}

$readzip = new ZipArchive;
if ($readzip->open('test.zip') === TRUE) {
    $readzip->extractTo('/my/destination/dir/');
    $readzip->close();
    echo 'ok';
}
else {
    echo 'failed';
}
?>
Dominic Rodger