How to ZIP files in Drupal 8

May 17, 2019
By Ihor

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:


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:

// Load 10 permanent files.
$ids = \Drupal::entityQuery('file')
  ->condition('status', 1)
  ->range(0, 10)
$files = \Drupal::entityTypeManager()
$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
$zip_file_uri = file_unmanaged_save_data('', 'public://test/', FILE_EXISTS_RENAME);
if (!$zip_file_uri) {
  drupal_set_message('Can\'t create zip file', 'error');

// 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);

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.

Developer with 8 years of experience in developing web applications. His extensive expertise in web application integration with third-party services allowed him to succeed working on e-commerce projects, sites for startups, sites for Medicine & Health companies.


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