压缩目录中的所有文件并下载生成的.zip

Ygo*_*gro 29 php directory zip ziparchive

好吧,首先,这是我的文件夹结构:

images/

image1.png
image11.png
image111.png
image223.png
generate_zip.php
Run Code Online (Sandbox Code Playgroud)

这是我的generate_zip.php:

<?php

    $files = array($listfiles);

    $zipname = 'adcs.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='adcs.zip'");
    header('Content-Length: ' . filesize($zipname));
    header("Location: adcs.zip");

    ?>
Run Code Online (Sandbox Code Playgroud)

如何收集"images /"文件夹中的所有文件,"generate_zip.php"除外,并使其成为可下载的.zip文件?在这种情况下,"images /"文件夹始终具有不同的图像.那可能吗?

T.T*_*dua 58

=======工作解决方案!======

包括所有子文件夹:

new GoodZipArchive('path/to/input/folder',    'path/to/output_zip_file.zip') ;
Run Code Online (Sandbox Code Playgroud)

首先,包括这段代码.

  • 如果这是最好的解决方案,我不知道,但我+ 1'它因为这对我有用 (2认同)

skr*_*led 26

这将确保不会添加扩展名为.php的文件:

   foreach ($files as $file) {
        if(!strstr($file,'.php')) $zip->addFile($file);
    }
Run Code Online (Sandbox Code Playgroud)

编辑:这里是重写的完整代码:

<?php

    $zipname = 'adcs.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);
    if ($handle = opendir('.')) {
      while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != ".." && !strstr($entry,'.php')) {
            $zip->addFile($entry);
        }
      }
      closedir($handle);
    }

    $zip->close();

    header('Content-Type: application/zip');
    header("Content-Disposition: attachment; filename='adcs.zip'");
    header('Content-Length: ' . filesize($zipname));
    header("Location: adcs.zip");

    ?>
Run Code Online (Sandbox Code Playgroud)