2010-12-22 129 views
0

目前,当涉及到多个小文件时,FTP在我们的服务器上非常慢。php递归压缩?

我想创建一个文件,我可以在创建zip文件的浏览器中运行该文件。

基本上这个文件将坐/ htdocs目录

zip文件中它创建必须采取/ htdocss(和子文件夹ECT)的所有文件和模仿的结构。

任何人都可以指向正确的方向吗?

我正在尝试使用下面的代码。

唯一的问题是, 我得到一些空白文件夹

说,该文件是:

C:/xampp/htdocs/booking/zip.php

我得到 /C
/C/XAMPP
/C/xampp/htdocs
/C/xampp/htdocs/booking
/C/xampp/htdocs/booking/image.png
/C/xampp/htdocs/booking/index.php

我不想/C/xampp/htdocs/booking

我只想zip文件包含 image.png 的index.php

如何解决这个?

<?php 

function Zip($source, $destination) { 
    if(extension_loaded('zip') === true) { 
    if(file_exists($source) === true) { 
     $zip = new ZipArchive(); 

     if($zip->open($destination, ZIPARCHIVE::CREATE) === true) { 
     $source = realpath($source); 

     if(is_dir($source) === true) { 
      $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); 

      foreach($files as $file) { 
      $file = realpath($file); 

      if(is_dir($file) === true) { 
       $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); 
      } else if(is_file($file) === true) { 
       $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); 
      } 
      } 
     } else if(is_file($source) === true) { 
      $zip->addFromString(basename($source), file_get_contents($source)); 
     } 
     } 

     return $zip->close(); 
    } 
    } 

    return false; 
} 

Zip(dirname(__FILE__), 'testzip.zip'); 
?> 
+0

Windows或* NIX?虽然PHP具有本机ZIP支持,但如果可用,调用操作系统的“zip”命令可能更容易。 – deceze 2010-12-22 02:28:14

回答

2

有两种选择。您可以使用内置的ZipArchive PHP并手动迭代目录内容(readdir或DirectoryIterator)。

或者你也可以做懒家伙:

header("Content-Type: archive/zip"); // mime 2.0 
header("Content-Disposition: attachment; filename=dir.zip"); 
passthru("zip -q -r - ."); 

取决于所安装的zip工具。它抱怨,如果你在终端上尝试,但应该通过passthru管道工作。

+0

这给了我一个空的zip – Hailwood 2010-12-22 02:39:57