Zip Stream in PHP

If your web server is running Linux, then you can do it streaming without a temp file being generated. Under Win32, you may need to use Cygwin or something similar.

If you use - as the zip file name, it will compress to STDOUT. That can be redirected straight to the requester using passthru(). The -q argument simply tells zip to not output the status text it normally would. See the zip(1) manpage for more info.

$zipfilename="zip_file_name.zip";

$files = array();

$target="/some/directory/of/files/you/want/to/zip";

$d = dir( $target );

while( false !== ( $entry = $d->read() ) )
{
    if( substr( $entry, 0, 1 ) != '.' && !is_dir( $entry ) ) 
    {
        $files[] = $entry;
    }
}

if( ! $files )
{
    exit( 'No files to zip.' );
}

header( 'Content-Type: application/x-zip' );
header( "Content-Disposition: attachment; filename=\"$zipfilename\"" );

$filespec="";

foreach( $files as $entry )
{
    $filespec .= ' ' . escapeshellarg( $entry );
}

chdir( $target );

passthru( "zip -q -$filespec" );

Leave a Comment