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

2022-01-01 00:00:00 directory zip php ziparchive

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

Well, first of all, this is my folder structure:

images/

image1.png
image11.png
image111.png
image223.png
generate_zip.php

这是我的 generate_zip.php:

And this is mine 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");

    ?>

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

How to gather all the files from "images/" folder, except "generate_zip.php", and make it a downloadable .zip? In this case the "images/" folder always have a different image. Is that possible?

推荐答案

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

this will ensure a file with .php extension will not be added:

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

这是重写的完整代码:

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

    ?>

相关文章