Created
March 16, 2021 19:42
-
-
Save MatzeKitt/384557fb2159ccff0d66c51a651c2cad to your computer and use it in GitHub Desktop.
Zip a directory via PHP with limited memory usage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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