2013-03-04 93 views
0

我是新來的SO和PHP新手。我在網上找到一個腳本來壓縮一個目錄,並且我編輯了它,以便它將zip發送到瀏覽器進行下載,然後從服務器上刪除該文件。如何將此腳本更改爲壓縮數組的dirs?

它正常工作,但是我想壓縮多個目錄,而不只是一個。

如何將我需要改變我的腳本來完成呢?

$date = date('Y-m-d'); 

$dirToBackup = "content"; 
$dest = "backups/"; // make sure this directory exists! 
$filename = "backup-$date.zip"; 

$archive = $dest.$filename; 


function folderToZip($folder, &$zipFile, $subfolder = null) { 
    if ($zipFile == null) { 
     // no resource given, exit 
     return false; 
    } 
    // we check if $folder has a slash at its end, if not, we append one 
    $folder .= end(str_split($folder)) == "/" ? "" : "/"; 
    $subfolder .= end(str_split($subfolder)) == "/" ? "" : "/"; 
    // we start by going through all files in $folder 
    $handle = opendir($folder); 
    while ($f = readdir($handle)) { 
     if ($f != "." && $f != "..") { 
      if (is_file($folder . $f)) { 
       // if we find a file, store it 
       // if we have a subfolder, store it there 
       if ($subfolder != null) 
        $zipFile->addFile($folder . $f, $subfolder . $f); 
       else 
        $zipFile->addFile($folder . $f); 
      } elseif (is_dir($folder . $f)) { 
       // if we find a folder, create a folder in the zip 
       $zipFile->addEmptyDir($f); 
       // and call the function again 
       folderToZip($folder . $f, $zipFile, $f); 
      } 
     } 
    } 
} 

// create the zip 
$z = new ZipArchive(); 
$z->open($archive, ZIPARCHIVE::CREATE); 
folderToZip($dirToBackup, $z); 
$z->close(); 

// download the zip file 
$file_name = basename($archive); 

header("Content-Type: application/zip"); 
header("Content-Disposition: attachment; filename=$file_name"); 
header("Content-Length: " . filesize($archive)); 

readfile($archive); 

// delete the file from the server 
unlink($archive); 
exit; 

感謝您的幫助!

伊爾瑪

回答

0

集$ dirToBackup到

$dirToBackup = array("restricted","ci"); 

然後:

foreach($dirToBackup as $d){ 
    folderToZip($d, $z, $d); 
} 

這就是所有。 問候,

+0

太感謝了,這有很大幫助。所有文件和文件夾都打包成一個zip文件。 但是說,如果我ZIP「文件夾1」和「文件夾2」,我怎麼會落得在zip文件結構是這樣的: 'zip文件: - 文件夾1 - folder2' – Iamirm 2013-03-05 15:05:31

+0

我通過傳遞第三個參數更正答案到folderToZip函數。 – 2013-03-08 21:59:21