Skip to content

Instantly share code, notes, and snippets.

@abelcallejo
Last active February 24, 2021 07:22
Show Gist options
  • Save abelcallejo/83c2a0d7c09c174182ae06bcdd53daac to your computer and use it in GitHub Desktop.
Save abelcallejo/83c2a0d7c09c174182ae06bcdd53daac to your computer and use it in GitHub Desktop.
Creating ZIP files using PHP

Creating ZIP files using PHP

<?php

/**
 * PREPARE THE PATHS AND FILE NAME
 *
 * Store the zip file to a common temporary location such as /tmp
 */
$zip_path = "/tmp";
$unique = uniqid(); // good enough for most cases, alternatively...
# $unique = md5( uniqid() . (new DateTime())->format('Y-m-d H:i:s:v').".z" ); // extremely more unique
$zip_file_name = "prefix-{$unique}.zip";
$zip_file = "{$zip_path}/{$zip_file_name}";

/**
 * CREATE THE ZIP ITSELF
 *
 * Very important!
 * The first parameter of the ZipArchive::open() method only works with relative paths.
 * It does not work with absolute paths.
 * That's why you need to set the working directory beforehand with the chdir() function.
 */
chdir( $zip_path );
$zip = new ZipArchive();
$zip->open( $zip_file_name, ZipArchive::CREATE );

/**
 * ADD FILES TO BE COMPRESSED
 */
$files = array( "/path/to/file-a.csv", "/path/to/file-b.txt" ); // list the files you want to be zipped
foreach ( $files as $file ) {
	$name_and_ext = basename( $file );
	$zip->addFile( $file, "/{$name_and_ext}" ); // use the second parameter to specify the file's target location inside the zip
}
$zip->close();

/**
 * DELIVER THE ZIP FILE TO THE BROWSER
 */
ob_clean();
ob_end_flush();
header( "Content-Type: application/zip" );
header( "Content-disposition: attachment; filename={$zip_file_name}" );
readfile( $zip_file );

?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment