Skip to content

Example function to archive directory tree

Viktor Szépe edited this page May 21, 2015 · 1 revision
archive_stream_zip_directory( '/home/web/public_html', 'web-html.zip' );

function archive_stream_zip_directory( $root, $archive = 'archive.zip' ) {
    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;
}
Clone this wiki locally