Skip to content

Instantly share code, notes, and snippets.

@kasparsd
Last active January 16, 2024 09:10
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 kasparsd/983b517b190f8bceb7cb2614942dc520 to your computer and use it in GitHub Desktop.
Save kasparsd/983b517b190f8bceb7cb2614942dc520 to your computer and use it in GitHub Desktop.
Zip chunks with PHP (split ZIP with max size)
<?php // Run as `php zip-chunks.php path/to/directory`.
$chunk_limit = 1024 * 1024 * 1024; // 1 GB
function get_files( $path ) {
$files = glob( rtrim( $path, '\\/' ) . '/*' );
foreach ( $files as $file ) {
if ( is_dir( $file ) ) {
$files = array_merge( $files, get_files( $file ) );
}
}
return array_filter( $files, 'is_file' );
}
// Zip all files in the current directory by default.
$lookup_path = getcwd();
// Allow specifying a custom path to a directory to zip.
if ( ! empty( $argv[1] ) ) {
$lookup_path = realpath( $argv[1] );
}
// Get all the file sizes.
$files = [];
foreach ( get_files( $lookup_path ) as $file ) {
$files[ $file ] = filesize( $file );
}
$chunks = [];
$chunk_size = 0;
foreach ( $files as $file => $filesize ) {
$chunk_size += $filesize;
$chunks[ floor( $chunk_size / $chunk_limit ) ][ $file ] = $filesize;
}
foreach ( $chunks as $chunk => $chunk_files ) {
printf(
'Creating chunk %d/%d (%d MB limit) with %d files (%d MB).' . "\n",
$chunk + 1,
count( $chunks ),
$chunk_limit / 1024 / 1024,
count( $chunk_files ),
array_sum( $chunk_files ) / 1024 / 1024
);
$zip = new ZipArchive();
$zip->open( sprintf( 'chunk-%d.zip', $chunk + 1 ), ZipArchive::CREATE );
foreach ( $chunk_files as $file => $filesize ) {
$zip->addFile( $file, str_replace( $lookup_path, '', $file ) );
}
$zip->close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment