【问题标题】:How to modify and download a compressed directory without altering changes to the original file in PHP?如何在不更改 PHP 中原始文件的更改的情况下修改和下载压缩目录?
【发布时间】:2017-08-04 15:10:57
【问题描述】:

我有一个包含一些文件和子目录的压缩目录。我想要实现的是修改压缩目录的内容,然后下载修改后的zip文件,这样在原来的zip文件里面就不会改动了。

例如,我想删除压缩目录中的特定文件,然后下载修改后的zip文件,使该文件仍然存在于原始压缩目录中。

到目前为止,这是我的代码。它工作正常,但问题是该文件也在原始压缩目录中被删除:

<?php

 $directoryPath = '/Users/Shared/SampleDirectory.zip';
 $fileToDelete = 'SampleDirectory/samplefile.txt';

 $zip = new ZipArchive();

 if ($zip->open($directoryPath) === true) {
     $zip->deleteName($fileToDelete);
     $zip->close();
 }    

 header('Content-Description: File Transfer');
 header('Content-Type: application/zip');
 header('Content-Disposition: attachment; filename="' . basename('SampleDirectory.zip') . '"');
 header('Content-Length: ' . filesize('SampleDirectory.zip'));;
 readfile('SampleDirectory.zip');

?>

如何实现所需的功能?

【问题讨论】:

    标签: php file download directory zip


    【解决方案1】:

    所有 zip 函数都会更改 zip 文件的内容。最简单的方法是使用 PHP 的 copy() 函数在临时位置创建文件副本并对该文件进行更改。完成后,您可以使用tempnam() 来避免名称冲突和unlink() 文件。

    这是一个例子:

    $directoryPath = '/Users/Shared/SampleDirectory.zip';
    $fileToDelete = 'SampleDirectory/samplefile.txt';
    
    $temp = tempnam('/tmp');
    copy($directoryPath, $temp);
    
    $zip = new ZipArchive();
    
    if ($zip->open($temp) === true) {
     $zip->deleteName($fileToDelete);
     $zip->close();
    }    
    
    header('Content-Description: File Transfer');
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="'.basename('SampleDirectory.zip').'"');
    header('Content-Length: ' . filesize($temp));
    readfile($temp);
    
    unlink($temp);
    

    警告:未经测试的代码,请确保您已备份文件。

    【讨论】:

      猜你喜欢
      • 2015-07-26
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 2013-11-19
      相关资源
      最近更新 更多