PHP ZipArchive Corrupt in Windows

I had this same problem, and my solution was similar to the correct answer on this thread. When you put a file in the archive, you can't have absolute files (files starting with a slash) or else it won't open in Windows for some reason.

So got it working not because he (Jesse Bunch, the selected answer at the time of this writing) removed the containing folder but because he removed the starting slash.

I fixed the issue by changing

$zip->addFile($file, $file); // $file is something like /path/to/file.png

to

// we make file relative by removing beginning slash so it will open in Windows
$zip->addFile($file, ltrim($file, '/'));

and then it was able to open in Windows!

That's probably the same reason pclzip (Plahcinski's answer) works. I bet it automatically strips off the beginning slash.

I wouldn't have figured this out without a particular comment on the PHP ZipArchive::addFile documentation page.


I recently had a similar issue as you described. I found ZipArchive to be unstable at best.

I solved my problems with this simple library

http://www.phpconcept.net/pclzip

include_once('libs/pclzip.lib.php');

...

function zip($source, $destination){
$zipfile = new PclZip($destination);
$v_list = $zipfile->create($source, '', $source); }

$source = folder i wanted to zip $destination = zip file location

I spent 2 days looking to ZipArchive and then solved all problems with PCLZip in 5 minutes.

Hope this helps you and anyone else having this issue (as this is near the top google result on the issue).


Ok, after much strife, I figured out the problem. The issue comes from the following line of code:

$objZip->addFile($filename,sprintf('/press_photos/%s-%s', $objPhoto->getEntryID(), basename($filename)));

For some reason, the /press_photos/ part of that path for the local (internal) file name inside the zip archive was causing Windows to think the zip file was corrupt. After modifying the line to look like what is below, Windows opened the zip files correctly. Phew.

$objZip->addFile($filename,sprintf('%s-%s', $objPhoto->getEntryID(), basename($filename)));

All of this suggestions may help you, but in my case I need to write an ob_clean(); before first header(''); because some file that I include before print some characters that broken zip file on windows.

$zip=new ZipArchive();
$zip->open($filename, ZIPARCHIVE::CREATE);
$zip->addFile($file_to_attach,$real_file_name_to_attach);
$zip->close();

ob_clean();
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header('Content-Type: application/x-download');
header('Content-Disposition: attachment; filename="file.zip"');
readfile($filename);
exit;