0

I am creating a module for Drupal 8, in which I want to upload and extract zip file to a root directory. Inside moduleSettingsForm.php file, I have a function submitForm(array &$form, FormStateInterface $form_state). I am getting all the values of uploaded file but I am unable to extract the content of file.

So is there any way to do this in Drupal 8?

1
  • Checking the Drupal 8 core docs, I've found a Zip class which might work for this purpose. Please see the documentation here.
    – Scorchio
    Jan 13 '16 at 12:47
3

Once you have the file uri of the uploaded file, this stops being a Drupal problem and starts being a PHP problem.

You should take a look at SO for a full description.

What you are looking for is this snippet.

$zip = new ZipArchive;
$res = $zip->open('file.zip'); 
if ($res === TRUE) {
  $zip->extractTo('/myzips/extract_path/');
  $zip->close();
}
1
  • "$zip = new \ZipArchive" worked Thanks a lot!! Jan 14 '16 at 12:37
2

There are a Drupal 8 Way how to unzip a ZIP archive:

use Drupal\Core\Archiver\Zip;
use Drupal\Core\Archiver\ArchiverException;

try {
  $zip = new Zip('/path/to/archive/file.zip');
  $zip->extract('/path/to/archive');
  // Remove the source zip file if necessary.
  // $zip->remove($file);
  // Shows list (array) of those unzipped files regarding the zip file folder.
  var_dump($zip->listContents());
}
catch (ArchiverException $exception) {
  watchdog_exception('custom_module_name', $exception);
  // Some code if the error of unzip will happen.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.