使用php压缩和下载文件

Pha*_*ani 6 php zip

我正在尝试压缩并从名为"upload"的文件夹下载文件.Zip文件正在下载但我无法打开(提取)它.我收到的错误如"存档格式未知或已损坏".

我找到了以下代码来压缩文件夹.

<?php
    $files = "upload/".array('Dear GP.docx','ecommerce.doc');
    $zipname = 'filename.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);
    foreach ($files as $file) {
      $zip->addFile($file);
    }
    $zip->close();
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename=filename.zip');
    header('Content-Length: ' . filesize($zipfilename));
    readfile($zipname);
?>
Run Code Online (Sandbox Code Playgroud)

Pha*_*ani 21

谢谢你的回答.

<?php
    $files = array('Dear GP.docx','ecommerce.doc');

    # create new zip opbject
    $zip = new ZipArchive();

    # create a temp file & open it
    $tmp_file = tempnam('.','');
    $zip->open($tmp_file, ZipArchive::CREATE);

    # loop through each file
    foreach($files as $file){

        # download file
        $download_file = file_get_contents($file);

        #add it to the zip
        $zip->addFromString(basename($file),$download_file);

    }

    # close zip
    $zip->close();

    # send the file to the browser as a download
    header('Content-disposition: attachment; filename=Resumes.zip');
    header('Content-type: application/zip');
    readfile($tmp_file);
 ?>
Run Code Online (Sandbox Code Playgroud)