简体   繁体   English

使用php覆盖zip文件

[英]overwrite zip file using php

I wrote a method to create a zip entry and rewrite it if this function is called second time but it is not working. 我编写了一种方法来创建一个zip条目,并在第二次调用此函数但不起作用时将其重写。 here is my code: 这是我的代码:

public function zipFile($filepath,$fileName){ 
    $zip = new ZipArchive;

    $zip_name = $fileName.'.zip';       

    echo "$zip_name";          

         if($zip->open($zip_name, ZIPARCHIVE::OVERWRITE)===TRUE) {

     $zip->addFile($filepath,$fileName.'.csv');
     $zip->close();
     echo 'ok';
          } else {
     echo 'failed';
                   }       
          return '/home/daily_reports/'.$zip_name;

                          } 

what is missing in my logic. 我的逻辑中缺少什么。 I want to replace the file with new one if the method is called again 如果要再次调用该方法,我想用新文件替换该文件

Perhaps try explicitly deleting the zip file first if it exists. 也许尝试先明确删除zip文件(如果存在)。 The overwrite option may not behave as expected. 覆盖选项可能无法按预期方式运行。

clearstatcache();//For good measure clear out any cached file paths

$file = "{$filepath}/{$fileName}"
if(file_exists($file)){
    unlink($file);
}

However, I have had mysterious issues trying to use the built-in zip functionality in php, especially with platform differences, performance, and memory issues. 但是,我在尝试使用php中的内置zip功能时遇到了一些神秘的问题,尤其是平台差异,性能和内存问题。 I prefer to zip the files on the command line through php. 我更喜欢通过php在命令行上压缩文件。

On linux/osx: 在linux / osx上:

$cmd = "zip archivefile file1 file2";
exec($cmd);

On windows use 7zip, also from the command line. 在Windows上,也从命令行使用7zip。 http://www.dotnetperls.com/7-zip-examples http://www.dotnetperls.com/7-zip-examples

$cmd = "7za.exe a archivefile.7z file1 file2";
exec($cmd);

Technically you don't need to install 7zip, you just need the stand alone exe, but you might need to install it first to get the exe. 从技术上讲,您不需要安装7zip,只需要独立的exe,但是您可能需要先安装它才能获得exe。 http://www.7-zip.org/download.html http://www.7-zip.org/download.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM