How to zip files in Drupal

Components

Creating a zip archive in Drupal is easy. First, make sure that your PHP is compiled with ZIP support, then prepare the directory where you want to create a zip file, and finally create the zip file.

In the following example, I'm creating a zip archive by adding the file uploaded in the field_file field.

use Drupal\node\NodeInterface;
use Drupal\Core\File\FileSystemInterface;

function MY_MODULE_create_zip_file(NodeInterface $node) {
  // Check if ZipArchive class exists.
  if (!class_exists('ZipArchive')) {
    \Drupal::logger('MY_MODULE')->warning('Could not compress file, PHP is compiled without zip support.');
  }

  // Prepare destination directory.
  $directory = 'public://node-zip-files/' . $node->bundle();
  $file_system = \Drupal::service('file_system');
  $file_system->prepareDirectory($directory, FileSystemInterface:: CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);

  // Open zip archive.
  $zip = new \ZipArchive();
  $zip_filename = $file_system->realpath($directory . '/' . $node->id() . '.zip');
  $result = $zip->open($zip_filename, constant('ZipArchive::CREATE'));
  if (!$result) {
    \Drupal::logger('MY_MODULE')->warning('Zip archive could not be created. Error: ' . $result);
  }

  // Add file uploaded to the provided node to the zip acrhive.
  $file = $node->get('field_file')->entity;
  $filepath = $file_system->realpath($file->getFileUri());
  $result = $zip->addFile($filepath, basename($file->getFileUri()));
  if (!$result) {
    \Drupal::logger('MY_MODULE')->warning('File could not be added to zip archive.');
  }

  // Close zip archive.
  $result = $zip->close();
  if (!$result) {
    \Drupal::logger('MY_MODULE')->warning('Zip archive could not be closed.');
  }
}

This function can be used like this:

$node = \Drupal::entityTypeManager()->getStorage('node')->load(SOME_NODE_ID);
MY_MODULE_create_zip_file($node);

The zip file will be created in the following directory: public://node-zip-files/NODE_BUNDLE/SOME_NODE_ID.zip

About the Author

Goran Nikolovski is an experienced web and AI developer skilled in Drupal, React, and React Native. He founded this website and enjoys sharing his knowledge.