2012-03-26 59 views
0

我使用這個功能來生成zip文件:拉鍊生成函數生成空白文件

function create_zip($files = array(),$destination = '',$overwrite = false) { 
    //if the zip file already exists and overwrite is false, return false 
    if(file_exists($destination) && !$overwrite) { return false; } 
    //vars 
    $valid_files = array(); 
    //if files were passed in... 
    if(is_array($files)) { 
    //cycle through each file 
    foreach($files as $file) { 
     //make sure the file exists 
     if(file_exists($file)) { 
     $valid_files[] = $file; 
     } 
    } 
    } 
    //if we have good files... 
    if(count($valid_files)) { 
    //create the archive 
    $zip = new ZipArchive(); 
    if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { 
     return false; 
    } 
    //add the files 
    foreach($valid_files as $file) { 
     $zip->addFile($file,$file); 
     //echo $file; 
    } 
    //debug 
    //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status; 

    //close the zip -- done! 
    $zip->close(); 

    //check to make sure the file exists 
    echo $destination; 
    return file_exists($destination); 
    } 
    else 
    { 
    return false; 
    } 
} 

我用這來壓縮香草,不變的WordPress安裝(http://wordpress.org/)然而由於某些原因,wp-content文件夾有一個由其名稱生成的'ghost'空文件。該文件夾(以及其他所有文件)本身壓縮正確,但是由於名稱衝突,大多數解壓縮應用程序(包括php自己的extractTo())在到達此不需要的文件時會中斷。

我已經查看了文件夾/文件結構,並且據我所見,此站點與站點中其他文件夾之間唯一的區別在於它在5.86 MB處最大。

任何人都可以提出修復/解決方法嗎?

+0

您可以在這裏嘗試郵編功能:http://stackoverflow.com/questions/1334613/how-to-recursively-zip-a-directory-in-php – 2012-03-26 12:55:17

+0

是否$文件陣列只包含文件還是目錄?也許你想添加'is_file'到你的'file_exists'檢查。 '$ zip-> addFile($ file)'應該足夠了(離開localname參數)。 – initall 2012-03-26 12:58:14

+0

錯誤日誌中是否有內容? – piotrekkr 2012-03-26 13:03:22

回答

0

這是壓縮文件夾的示例示例。

 <?php 
     function Create_zipArch($archive_name, $archive_folder) 
     { 
      $zip = new ZipArchive; 
      if ($zip->open($archive_name, ZipArchive::CREATE) === TRUE) 
      { 
       $dir = preg_replace('/[\/]{2,}/', '/', $archive_folder . "/"); 

       $dirs = array($dir); 
       while (count($dirs)) 
       { 
        $dir = current($dirs); 
        $zip->addEmptyDir($dir); 

        $dh = opendir($dir); 
        while ($file = readdir($dh)) 
        { 
         if ($file != '.' && $file != '..') 
         { 
          if (is_file($file)) 
           $zip->addFile($dir . $file, $dir . $file); 
          elseif (is_dir($file)) 
           $dirs[] = $dir . $file . "/"; 
         } 
        } 
        closedir($dh); 
        array_shift($dirs); 
       } 

       $zip->close(); 
       $result='success'; 
      } 
      else 
      { 
       $result='failed'; 
      } 
      return $result; 
     } 

     $zipArchName = "ZipFileName.zip"; // zip file name 
     $FolderToZip = "zipthisfolder"; // folder to zip 

     echo Create_zipArch($zipArchName, $FolderToZip); 
     ?>