【问题标题】:ZipArchive downloading empty zip filesZipArchive 下载空的 zip 文件
【发布时间】:2023-04-07 09:24:01
【问题描述】:

我正在尝试创建一个包含简单文本文件的 zip 文件。不幸的是,当我打开 zip 文件时,该文件是空的,尽管在代码中我已添加到文本文件中。

我一直在寻找有关该主题的其他问题但无济于事,我尝试添加不同的文件,例如照片,但 zip 始终为空。

我怎样才能成功地将文件添加到我的 zip 中?

这里是注释代码


if($_POST['down']){

  ob_clean(); //clean and flush
  ob_end_flush();
  
  $zip = new ZipArchive(); //create new zip 
  $filename = 'images.zip'; //call the zip a name
  
  if($zip->open($filename, ZipArchive::CREATE) == FALSE){  //if zip can't be opened or created, kill the script
      die('nozip');
  }
  
  
  $string = 'wef2emfofp32fo2mfomepofm'; // a string 
  $zip->addFromString('text.txt', $string); //add the string to the zip
  $zip->close(); //close zip
  

    header("Content-Disposition: attachment; filename=".basename(str_replace(' ', '_', $filename)));
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/zip");
    header("Content-Description: File Transfer");
    header("Content-Length: " . filesize($filename));

    //download the zip
  
}

【问题讨论】:

    标签: php download zip ziparchive


    【解决方案1】:
    With this simple code (from php documentaion)
    
    I have created succesfully the zip and the content
    
    <?php
    $zip = new ZipArchive;
    $res = $zip->open('test.zip', ZipArchive::CREATE);
    if ($res === TRUE) {
        $zip->addFromString('test.txt', 'file content goes here');
        $zip->close();
        echo 'ok';
    } else {
        echo 'failed';
    }
    ?>
    

    【讨论】:

      【解决方案2】:

      删除这些代码

        if($zip->open($filename, ZipArchive::CREATE) == FALSE){  //if zip can't be opened or created, kill the script
        die('nozip');
      

      }

      并用 try catch 块包围其他所有内容。如果该块本身不是原因,您可能会在异常消息中找到答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-28
        • 1970-01-01
        • 2018-12-06
        • 2020-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多