单击按钮时,将所有文件下载为zip

时间:2016-04-16 15:47:15

标签: php

我无法理解我的按钮应该如何显示并触发下载文件为zip。在页面上,我可以在某种类型的购物车中添加文件,当我完成文件添加时,我想像zip一样下载它们。

所以我到目前为止就是这个

<?php
include 'database.inc.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if(isset($_POST['total_cart_items']))
{
   echo count($_SESSION['itemid']);
   exit();
}

if(isset($_POST['item_id']))
{    
    if (!in_array($_POST['item_id'], $_SESSION['itemid'])) $_SESSION['itemid'][]=$_POST['item_id'];
    echo count($_SESSION['itemid']);
    exit();
}  

if(! isset($_POST['showcart'])) exit;
foreach ($_SESSION['itemid'] as $i):

    $sql = "SELECT * FROM document_upload WHERE upload_id = :id"; 
    $result = $pdo->prepare($sql);
    $result->bindParam(":id", $i);
    $result->execute();                 

    $resArray = $result->fetchAll();

     foreach ( $resArray as $row ):?>

         <div class="cart_items">
              <a style="text-align:center;" href=""><p><?=$row["upload_title"]?> - <?=$row["upload_description"]?></p></a>
         </div>
    <?php endforeach;?>
 <?php endforeach; ?>
         <a class="btn btn-info btn-sm pull-right" style="margin: 10px;" href="">Download All Files</a>

所以我需要另一个文件,当我点击Download All Files或?

时会加载该文件 编辑:我发现了这个。问题是如何将所有文件传递给这个函数?

session_start();
$files = array();

$valid_files = array();
if(is_array($files)) {
  foreach($files as $file) {
    if(file_exists($file)) {
        $valid_files[] = $file;
    }
  }
}

if(count($valid_files > 0)){
   $zip = new ZipArchive();
   $zip_name = "zipfile.zip";
   if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
      $error .= "* Sorry ZIP creation failed at this time";
}

foreach($valid_files as $file){
    $zip->addFile($file);
}

$zip->close();
if(file_exists($zip_name)){
    // force to download the zip
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename="'.$zip_name.'"');
    readfile($zip_name);
    // remove zip file from temp path
    unlink($zip_name);
}

} else {
    echo "No valid files to zip";
    exit;
}

0 个答案:

没有答案