2017-08-28 60 views
3

編輯:這個問題在下面回答。如果你想ZIP的目錄/文件夾就像我所做的,看到這個:How to zip a whole folder using PHP文件添加到現有的ZIP文件

我有一個應用程序自動從我的服務器下載一個ZIP文件的計時器。

但ZIP文件每天都被改變了。

當有人使用的應用程序,因爲去除ZIP文件並重新添加(因爲應用程序定時器每900毫秒執行的是)的應用程序的用戶將得到一個「550文件不可用」錯誤。

所以不是刪除ZIP文件,並用新的數據重新創造它,如何添加,而無需重新創建ZIP文件中的新數據?

目前我使用這個:

$zip = new ZipArchive; 
// Get real path for our folder 
$rootPath = realpath('../files_to_be_in_zip'); 

// Initialize archive object 
$zip = new ZipArchive(); 
$zip->open('../zouch.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); 

// Create recursive directory iterator 
/** @var SplFileInfo[] $files */ 
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath), 
    RecursiveIteratorIterator::LEAVES_ONLY 
); 

foreach ($files as $name => $file) 
{ 
    // Skip directories (they would be added automatically) 
    if (!$file->isDir()) 
    { 
     // Get real and relative path for current file 
     $filePath = $file->getRealPath(); 
     $relativePath = substr($filePath, strlen($rootPath) + 1); 

     // Add current file to archive 
     $zip->addFile($filePath, $relativePath); 
    } 
} 

// Zip archive will be created only after closing object 
$zip->close(); 

而這個代碼得到files_to_be_in_zip文件夾的內容,並重新使用它創建了「zouch.zip」文件。

是的,我知道新的數據FULLPATH ......這是$recentlyCreatedFile

編輯:我發現這個代碼在http://php.net/manual/en/ziparchive.addfile.php

<?php 
$zip = new ZipArchive; 
if ($zip->open('test.zip') === TRUE) { 
    $zip->addFile('/path/to/index.txt', 'newname.txt'); 
    $zip->close(); 
    echo 'ok'; 
} else { 
    echo 'failed'; 
} 
?> 

但我想創建一個目錄現有的ZIP也是如此。

任何幫助嗎?

謝謝!

回答

2

當你打開zip,您指定爲它要麼被新創建或在你的第二個參數覆蓋。刪除第二個參數應該使您的腳本按原樣運行。以下是您的代碼,其中已經實施了所需的編輯。

$zip = new ZipArchive; 
// Get real path for our folder 
$rootPath = realpath('../files_to_be_in_zip'); 

$zip->open('../zouch.zip'); 

// Create recursive directory iterator 
/** @var SplFileInfo[] $files */ 
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath), 
    RecursiveIteratorIterator::LEAVES_ONLY 
); 

foreach ($files as $name => $file){ 
    // Skip directories (they would be added automatically) 
    if (!$file->isDir()){ 
    // Get real and relative path for current file 
    $filePath = $file->getRealPath(); 
    $relativePath = substr($filePath, strlen($rootPath) + 1); 

    // Add current file to archive 
    $zip->addFile($filePath, $relativePath); 
    } 
} 

// Zip archive will be created only after closing object 
$zip->close(); 

不過,如果你有一個已經在ZIP文件,但將需要在未來要被替換的數據,那麼你必須使用ZipArchive::OVERWRITE

$zip->open('../zouch.zip', ZipArchive::OVERWRITE); 
+0

卸下'ZipArchive :: CREATE | ZipArchive :: OVERWRITE'參數修復了一切!非常感謝:-) – MatrixCow08

+0

高興地幫助,感謝您及時接受答案。 – coderodour

相關問題