简体   繁体   English

在php中创建和下载zip存档

[英]create and download zip archive in php

I have created a zip file and download that. 我创建了一个zip文件并下载了。 But my problem is that I just want to download specific files not the complete files of the root folder. 但是我的问题是我只想下载特定文件而不是根文件夹的完整文件。

My code is 我的代码是

$zipname = 'documents.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($allDocuments as $document) {
  $filetopath = public_path().$document;
  $filename = explode('/',$document);
  $name = end($filename);
  $zip->addFile($filetopath,$name);
 }
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname); 

I just want to make a zip file which has only files named, not any folder and have specific files not all files of the root folder. 我只想制作一个仅包含命名文件的zip文件,而不包含任何文件夹,并且包含特定文件而不是根文件夹的所有文件。 But I am getting all folder and all files by this. 但是我由此得到了所有文件夹和所有文件。

In $alldocumnets variable I am getting a limited record, not all records. 在$ alldocumnets变量中,我得到的是有限记录,而不是所有记录。 But when creating zip it gets all files. 但是在创建zip时会获取所有文件。

I don't understand where I am getting wrong. 我不明白我在哪里弄错了。

The question about the directories is clear: just exclude everything that is_dir() == true 有关目录的问题很明确:只排除is_dir()== true的所有内容

<?php
$allDocuments = array("a.py","b.py");

$zipname = 'documents.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach($allDocuments as $document) {
  $filetopath = getcwd().'\\'.$document;
  if(!is_dir($filetopath)) {
    $filename = explode('/',$document);
    $name = end($filename);
    $zip->addFile($filetopath,$name);
  }
 }
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

Unfortunately, the second part is not clear. 不幸的是,第二部分不清楚。 As long as you do not tell us which files you intent do exclude or what's the exact problem this is unsalvageable. 只要您不告诉我们要排除的文件或确切的问题是什么,这都是无法挽回的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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