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.

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

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图