Skip to content

Instantly share code, notes, and snippets.

@MatzeKitt
Created March 16, 2021 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatzeKitt/384557fb2159ccff0d66c51a651c2cad to your computer and use it in GitHub Desktop.
Save MatzeKitt/384557fb2159ccff0d66c51a651c2cad to your computer and use it in GitHub Desktop.
Zip a directory via PHP with limited memory usage.
<?php
/**
* Configuration
*/
$filename = 'compressed.zip';
$path = '/path/to/store';
// special case for ALL-INKL
// $path = preg_replace( '/(\/www\/htdocs\/\w+\/).*/', '$1', realpath( __FILE__ ) ) . 'subdir';
/**
* Configuration end
*/
@ini_set( 'max_execution_time', 30000 );
@ini_set( 'memory_limit', '256M' );
zip_files( $path, './' . $filename );
function zip_files( $source, $destination ) {
$zip = new ZipArchive();
if ( $zip->open( $destination, ZIPARCHIVE::CREATE ) === true ) {
$source = realpath( $source );
if ( is_dir( $source ) ) {
$iterator = new RecursiveDirectoryIterator( $source );
$iterator->setFlags( RecursiveDirectoryIterator::SKIP_DOTS );
$files = new RecursiveIteratorIterator( $iterator, RecursiveIteratorIterator::SELF_FIRST );
foreach ( $files as $file ) {
$file = realpath( $file );
if ( is_dir( $file ) ) {
$zip->addEmptyDir( str_replace( $source . DIRECTORY_SEPARATOR, '', $file . DIRECTORY_SEPARATOR ) );
}
else if ( is_file( $file ) ) {
$zip->addFile( $file, str_replace( $source . DIRECTORY_SEPARATOR, '', $file ) );
}
}
}
else if ( is_file( $source ) ) {
$zip->addFile( $source, basename( $source ) );
}
}
return $zip->close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment