1

I am trying to create a zip file and download that zip file on a button click in WordPress but when I try to download the file it always throws error - Cannot modify header information - headers already sent by

Here is my code -

function downloadZipFile($file_array){
  # create new zip object
  $zip = new ZipArchive();
  # create a temp file & open it
  $tmp_file = tempnam('.', '');
  $zip->open($tmp_file, ZipArchive::CREATE);
  # loop through each file
  foreach ($file_array as $file) {
      //echo $file;
      # download file
      $download_file = file_get_contents($file);

      #add it to the zip
      $zip->addFromString(basename($file), $download_file);
  }
  # close zip
  $zip->close();
  # send the file to the browser as a download
  echo ABSPATH.'downloadZip.php';
  header('Content-disposition: attachment; filename="my file.zip"');
  header('Content-type: application/zip');
  readfile($tmp_file);
  unlink($tmp_file);
}

In the above function I am passing a file array which is coming from box api. I can see all files are coming fine from box api endpoint.

vivek kumar
  • 55
  • 1
  • 9
  • did you check if the file you are trying to zip have the permission ? – Yassine CHABLI Dec 31 '18 at 08:29
  • 2
    Possible duplicate of [How to fix "Headers already sent" error in PHP](https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – Yassine CHABLI Dec 31 '18 at 08:47
  • @MohammedYassineCHABLI Yes files are having permission. – vivek kumar Dec 31 '18 at 09:20
  • I don't think this is duplicate of https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php. I fixed this error by using ob_start() function in wp-config.php but my zip file is always empty. I think think this is a problem with box api because when I try with other API URL it works. I also found this link https://community.box.com/t5/Platform-and-Development-Forum/Download-file-as-zip-via-API/td-p/40954. – vivek kumar Dec 31 '18 at 09:30

0 Answers0