0

I'm trying to download a folder as zip but I always get a zip with 0 byte files. I tried all the solutions found on the internet but it did not help. This is the code:

  $files= scandir($dir);
  $zip = new ZipArchive();


  $tmp_file = tempnam('.','');
  if (  $zip->open($tmp_file, ZipArchive::CREATE)===TRUE) {
    # loop through each file
    foreach($files as $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
    header("Content-disposition: attachment; filename=$nome_dir.zip");
    header("Content-length: " . filesize($tmp_file));
    header('Content-type: application/zip');
    readfile($tmp_file);
  }

I can not understand where I'm wrong

  • Enable errors to see if there are any. See: https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display (or check the error log) – KIKO Software Jul 02 '18 at 09:35
  • display_errors is set to ON no error return…. – Alessandro Arcuri Jul 02 '18 at 10:02
  • Ok, put an echo at the top of the file. For instance: `echo "Hello world!";`. Does that end up in the output? If not then there might be a syntax error in your PHP. When there's a syntax error then switching on error reporting doesn't help, because the whole file simply doesn't get executed. The error logs will show the syntax error. If the echo does show up then there's a problem with the way you create the zip archive (I haven't looked into that yet, first things first). – KIKO Software Jul 02 '18 at 10:06
  • Thinking about it, if you do get a ZIP file, even if it is zero bytes, then your code must have executed.... sorry, should have thought of that. – KIKO Software Jul 02 '18 at 10:10
  • Well, there are some loose ends in your code: `$dir` is an unknown, are there any files in that directory? also `$nome_dir` is undefined. – KIKO Software Jul 02 '18 at 10:14
  • show result of var_dump($files); – step Jul 02 '18 at 10:15
  • $dir is the path where the files are located and is not empty ... $nome_dir is the name I want to give to the zip file... – Alessandro Arcuri Jul 02 '18 at 10:41
  • What you want to try, Zip the whole folder included files and folder or only files? – Jagjeet Singh Jul 02 '18 at 11:22
  • create a zip archive with the files contained in the folder – Alessandro Arcuri Jul 02 '18 at 11:50
  • I was also using `tempnam` with PHP 7.1 to create a temp file and I had the same issue. Removing `tempnam` and replacing it with a self-rolled function resolved this. Maybe related - dunno. – madflow May 12 '20 at 15:46

1 Answers1

0

This may be related to Memory Allocation issues in PHP, e.g. My PHP zip function is using too much memory

Also check this: https://www.airpair.com/php/fatal-error-allowed-memory-size

tertek
  • 890
  • 1
  • 10
  • 20