Andy Holmes
Andy Holmes

Reputation: 8047

PHP created ZIP file not working with Windows Explorer

I have the following code which works fine on windows with WinRAR and works fine on Mac's as well. However, for some reason, when you open it with the default windows Explorer, the zip appears empty and when you right click and extract, it says it is invalid. When the same one is opened with winrar or on a mac, all the files are there. Any ideas?

$passcode = $_GET['passcode'];

    $zip = new ZipArchive;
    $download = 'download_files_'.$passcode.'.zip';
    $zip->open($download, ZipArchive::CREATE);
    foreach (glob("../dashboard/uploads/".$passcode."/*.jpg") as $file) { /* Add appropriate path to read content of zip */
        $zip->addFile($file);
    }
    $zip->close();
    header('Content-Type: application/zip');
    header("Content-Disposition: attachment; filename = $download");
    header('Content-Length: ' . filesize($download));
    header("Location: $download");

Upvotes: 6

Views: 2170

Answers (4)

Fly
Fly

Reputation: 101

Another one related fix:

Linux is able to read a zip file with some html at the begin, you can use ob_clean() to clear unwanted code sent to the default output.

Upvotes: 0

2ge
2ge

Reputation: 281

just my $0.02 - Windows file manager doesn't like, if files in ZIP archives are stored with leading delimiter.

This doesn't work:

$zip->addFile(realpath($file), '/mydir/myfile.txt');

this works:

$zip->addFile(realpath($file), 'mydir/myfile.txt');

Upvotes: 2

Always 18
Always 18

Reputation: 41

You can solve this issue using following method.

foreach (glob("../dashboard/uploads/".$passcode."/*.jpg") as $file) { 
    $zip->addFile(realpath($file), pathinfo($file, PATHINFO_BASENAME));
}

I hope this helps you.

Upvotes: 2

Andy Holmes
Andy Holmes

Reputation: 8047

This was easily fixed by using the following method: I had to move the generate zip file to inside the uploads folder and remove ../dashboard/uploads/ as it was this path that was causing windows to think of it as a corrupt file

Upvotes: 0

Related Questions