简体   繁体   中英

How do I create zip file in PHP?

I want to create a zip file which contains some PDFs which are saved at my server.

Here is the code I tried,

$filenamez = 'datasheets1.zip';
$zip = new ZipArchive;

if ($zip->open('datasheets1.zip', ZipArchive::CREATE) === true) {
    // Add files to the zip file
    for ($m = 0; $m <= $total - 1; $m++) {

        $zip->addFile('datasheet' . $m, $model1[$m] . ".pdf");

    }

    $zip->close();

    echo 'Archive created!';
    header('Content-type: application/zip');
    header('Content-disposition: attachment;   filename="' . $filenamez . '"');
    header("Content-length: " . filesize($filenamez));
    readfile($filenamez);
}

When I execute this code the zip file is created and downloaded but when I open it shows following error: " this archive is either in unknown format or damaged ".

In addition to Andrei's comment, you're echoing the string 'Archived Created!', and then also setting an application/zip header, and then streaming the contents of the ZIP file to the browser. So the content of the ZIP will be polluted by having that string inserted at the top, making it corrupt.

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