I'm creating a custom form using Drupal 7 Form API, and I need my users to be able to select a ZIP file containing a number of other files. I'd like to be able to extract the files and then upload each individually, rather than uploading the zip file. I also need to ensure that all files within the zip file are of the correct type. This is my current attempt:

First I created the form:

function form_example_upload_files_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'managed_file',
    '#name' => 'files[]',
    '#title' => t('Upload Files'),
    '#upload_location' => $form_state['values']['upload_path'],
    '#upload_validators' => array(
      'file_validate_extensions' => array('xls xlsx txt zip'),
      'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
    '#process' => array('form_example_my_file_element_process')

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Upload Files'),

  return $form;

Then I created the submit function:

function form_example_upload_files_submit($form, &$form_state) {
  $file = file_load($form_state['values']['file']);
  $uri = $file->uri;
  $path_parts = pathinfo($uri);
  if ($path_parts['extension'] == "zip") {
    $path = explode("/", $uri);
    $new_path = "public://".$path[2]."/".$path[3]."/"; //This gives the upload file path

    $archiver = archiver_get_archiver($uri);
    $extracted_files = $archiver->listContents();
    /*Remove files with incorrect extensions from the archiver*/
    for ($i = 0; $i < count($extracted_files); $i++) {
      $parts = pathinfo($extracted_files[$i]);
      if ($parts['extension'] != "txt" and $parts['extension'] != "xls" and $parts['extension'] != "xlsx") {

    /*Extract all remaining files*/
    if (file_exists($uri)) {
      file_delete($file); //Delete the original zip file from the directory

The issue that I'm having is that the extraction and deletion are not occurring. The correct files are being removed from the zip file, as seen when I download and unzip the file. If I comment out the remove section but leave in the extract and delete section the zip file is correctly extracted and then deleted, but all files regardless of extension remain.

Does anyone know how to fix this issue? I'd really like to be able to unzip the file prior to uploading and then only upload files with the correct extensions, but I'd be fine with just extracting the files correctly. Thanks!

Your Answer

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

Browse other questions tagged or ask your own question.