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.

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

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器