Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZIP Archive sent by PHP is corrupted

Tags:

php

zip

I am using php ZipArchive to create an zip file on-the-fly and send it back to the user. I temporarily store the zipped file in a folder above document root and then send it back with the code

header('Content-type:application/zip');
header('Content-Disposition: inline; filename="'.("file.zip").'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length:".filesize($file));
$fh = fopen($file,'rb');
fpassthru($fh);

after having first issued a

$zip->close()

to ensure that that the file isn't open. The issue I have run into is this - the stored zip file is a valid archive which I can open in Windows 7, 7Zip, WinZIP etc. However, when I send the file down with the code above it ends up with an 0xD 0xA pair at the start of the file which is enough to render it corrupt. I cannot figure out where those characters could be coming from. Is this a known bug with fopen/fpassthru? Any help would be much appreciated.

like image 578
DroidOS Avatar asked Nov 28 '22 05:11

DroidOS


2 Answers

I found when removing the header("Content-Length:".filesize($file)); line it fixed my very same problem...

like image 96
on_ Avatar answered Dec 12 '22 07:12

on_


After many tries to download zip file, the solution was:

$result = create_zip($files_to_zip,$fileZip,true,$path_parts['dirname']);
ob_clean();
ob_end_flush(); // more important function - (without - error corrupted 
zip)
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header('Content-Type: application/zip;\n');
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=\"".basename($fileZip)."\"");
readfile($fileZip);
unlink($fileZip);
exit();
like image 29
WGab Avatar answered Dec 12 '22 08:12

WGab