Search code examples
phpzipphp-ziparchive

ZipArchive invalid in Windows only


I am using ZipArchive with the following code to create zip files. It works well in all browsers on a Mac. But it says the file is invalid on any browser on a Windows computer. I don't understand why. I emailed the supposedly corrupt file from the Windows computer to myself and opened it on my Mac computer, and it worked fine. I also read through all the suggestions on this thread and tried all of them, with no luck.

Do you see anything wrong with my code?

if(extension_loaded('zip')){     
    if(isset($post['afiles']) and count($post['afiles']) > 0){   
        $zip = new ZipArchive();    
        $url = get_stylesheet_directory();
        $filepath = $url;        
        $zip_name = "DSV".time().".zip";                 
        if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){        
            $error .=  "Error";
        }
        foreach($post['afiles'] as $file){
                    
            // get the file directory url from the file ID
            $path = get_attached_file( $file ); 
            
            // add each file to the zip file 
            $zip->addFile($path, basename($path));  
    
        }
        $zip->close();
        
        ob_clean();
        header('Content-type: application/zip');
        header('Content-Disposition: attachment; filename="'.$zip_name.'"'); 
        readfile($zip_name); 
        unlink($zip_name);
        
    }else
        $error .= "* Please select file to zip <br/><br />";
}else
    $error .= "* You do not have the ZIP extension<br/><br />";

I echoed basename($path) to confirm that there are no slashes. It is simply the filename like "this-is-my-file.docx". Thanks for any insight!

Edit: The exact error in Windows says:

Compressed (zipped) Folders Error
Windows cannot open the folder. The Compressed (zipped) Folder 'C:\Users\krist\Downloads\DWV1620652983.zip' is invalid.


Solution

  • After inspecting the ZIP files, there's HTML coming after the ZIP content. The fix is to make sure to call exit as soon as possible after calling readfile so that nothing else is written to the stream.