<?php

// get path to current file
$pwd = dirname(__FILE__);
// load zipstream class
require $pwd . '/../zipstream.php';
require $pwd . '/../tarstream.php';
// add some random files
$files = array('../extras/zip-appnote-6.3.1-20070411.txt', '../zipstream.php');
// create new zip stream object
$zip = new ArchiveStream_Zip('test.zip', array('comment' => 'this is a zip file comment.  hello?'));
// common file options
$file_opt = array('time' => time() - 2 * 3600, 'comment' => 'this is a file comment. hi!');
// add files under folder 'asdf'
foreach ($files as $file) {
    // build absolute path and get file data
    $path = $file[0] == '/' ? $file : "{$pwd}/{$file}";
    // add file to archive
    $zip->add_file_from_path('asdf/' . basename($file), $path, $file_opt);
}
// add a long file name
$zip->add_file('/long/' . str_repeat('a', 200) . '.txt', 'test');
$zip->add_directory('/foo');
$zip->add_directory('/foo/bar');
// finish archive
$zip->finish();
function archive_stream_zip_directory($root, $archive = 'archive.zip')
{
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    date_default_timezone_set('UTC');
    if (!class_exists('RecursiveIteratorIterator') || !function_exists('gzdeflate')) {
        return 1;
    }
    if (!file_exists($root)) {
        return 2;
    }
    if (function_exists('proc_nice')) {
        proc_nice(19);
    }
    $files = array();
    $added = array();
    $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root), RecursiveIteratorIterator::SELF_FIRST);
    $zip = new ArchiveStream_Zip($archive);
    foreach ($objects as $name => $object) {
        // http://php.net/manual/en/splfileinfo.getbasename.php
        $basename = $object->getBasename();
        if ('.' === $basename || '..' === $basename || $object->isDir()) {
            continue;
        }
        $zip->add_file_from_path(ltrim($name, '/'), $name);
        //DBG echo $name.'<br>';
        $added[] = $name;
    }
    $zip->finish();
    if (function_exists('proc_nice')) {
        proc_nice(0);
    }
    return $added;
}