简体   繁体   中英

create and download zip archive in php

I have created a zip file and download that. 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. But I am getting all folder and all files by this.

In $alldocumnets variable I am getting a limited record, not all records. But when creating zip it gets all files.

I don't understand where I am getting wrong.

The question about the directories is clear: just exclude everything that 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.

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