在php中创建和下载zip文件时出现错误

问题描述 投票:0回答:1

我正在尝试创建和下载zip文件,但是我想将特定文件压缩到应从数据库中选择的目录中。

此程序的作用是仅从school_homework中选择该主题的作业文件。

这实际上创建了一个zip文件,但是当我解压缩它时,它返回错误'此zip为空'!

while($row_file=mysqli_fetch_array($run_file)){
$school_homework_file_file=$row_file['school_homework_file_file'];

  $zip = new ZipArchive();
  $filename = "./homework.zip";

  if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
  }

  $dir = "$school_homework_file_file";

  // Create zip
  createZip($zip,$dir);

  $zip->close();

  }

  #Download Zip File
  $filename = "homework.zip";

  if (file_exists($filename)) {
     header('Content-Type: application/zip');
     header('Content-Disposition: attachment; filename="'.basename($filename).'"');
     header('Content-Length: ' . filesize($filename));

     flush();
     readfile($filename);
     // delete file
     unlink($filename);

   }

}

// Create zip
function createZip($zip,$dir){
  if (is_dir($dir)){

    if ($dh = opendir($dir)){
       while (($file = readdir($dh)) !== false){

         // If file
         if (is_file($dir.$file)) {
            if($file != '' && $file != '.' && $file != '..'){

               $zip->addFile($dir.$file);
            }
         }else{
            // If directory
            if(is_dir($dir.$file) ){

              if($file != '' && $file != '.' && $file != '..'){

                // Add empty directory
                $zip->addEmptyDir($dir.$file);

                $folder = $dir.$file.'/';

                // Read data of the folder
                createZip($zip,$folder);
              }
            }

         }

       }
       closedir($dh);
     }
  }
}
php mysql zip ziparchive
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.