How to ZIP files in Drupal 8

May 17, 2019
By Igor
Drupal

First of all, let's determine whether you have the PHP Zip extension installed. To get the list of the installed extensions, run the following PHP code:

<?php
print_r(get_loaded_extensions());
?>

If you can't find "zip" in the output, install the extension (for Ubuntu):

sudo apt-get update
sudo apt-get install php-zip
sudo service apache2 restart

Let's take a look at a simple code snippet for adding files to a Zip archive. This knowledge might save you time and make your web dev journey easier.

A code example for adding files to a Zip archive:

<?php
// Load 10 permanent files.
$ids = \Drupal::entityQuery('file')
  ->condition('status', 1)
  ->range(0, 10)
  ->sort('fid')
  ->execute();
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadMultiple($ids);
$file_system = \Drupal::service('file_system');

// Create empty file for ZipArchive (In Zip.php file open used without flags).
// @see core/lib/Drupal/Core/Archiver/Zip.php
// @see http://php.net/manual/ru/ziparchive.open.php
$zip_file_uri = file_unmanaged_save_data('', 'public://test/demo.zip', FILE_EXISTS_RENAME);
if (!$zip_file_uri) {
  drupal_set_message('Can\'t create zip file', 'error');
  return;
}

// Get ZipArchive object.
$zip = archiver_get_archiver($file_system->realpath($zip_file_uri))->getArchive();
// Add file to ZipArchive.
foreach ($files as $file) {
  // The name of the file inside the ZIP archive. If specified,
  // it will override filename.
  $localname = $file->getFilename();
  // $filename - path to the file to add.
  $filename = $file_system->realpath($file->getFileUri());
  $zip->addFile($filename, $localname);
}
$zip->close();
?>

Well done! I hope it’ll help you. Please don't forget to share the article with friends and colleagues if you like this little techie hack.

Igor
Team Lead and technology leader. Writes about Drupal, technologies and digital innovations.

LET'S CONNECT

Get a stunning website, integrate with your tools,
measure, optimize and focus on success!