简体   繁体   中英

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");

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.

通过使用以下方法可以很容易地解决这个问题:我必须将生成的zip文件移动到uploads文件夹中并删除../dashboard/uploads/ ,因为这条路径导致Windows将其视为损坏的文件

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');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM