dopuz8728 2017-03-14 10:22
浏览 24
已采纳

如何修改和下载压缩目录而不改变PHP中原始文件的更改?

I have a compressed directory which contains some files and subdirectories. What I want to achieve is to modify the content of the compressed directory and then download the modified zip file, so that the changes are not altered inside the original zip file.

For example, I want to delete a specific file inside the compressed directory and then download the modified zip file, so that the file still exists in the original compressed directory.

Here is my code so far. It works fine, but the problem is that the file is also deleted inside the original compressed directory :

<?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');

?>

How can I achieve the desired functionality?

  • 写回答

1条回答 默认 最新

  • dtvjl64442 2017-03-14 10:45
    关注

    All zip functions change the content of the zip file. The easiest way it to create a copy of the file at a temporary location using PHP's copy() function and operate the changes on that file. You can use tempnam() to avoid name conflicts and unlink() the file after you're done.

    Here's an example:

    $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);
    

    Warning: untested code, make sure you have backups to the files.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条