2017-03-14 22 views
0

我有一個包含一些文件和子目錄的壓縮目錄。我想要實現的是修改壓縮目錄的內容,然後下載修改後的zip文件,以便在原始zip文件內部不會更改這些更改。如何修改和下載壓縮目錄而不更改PHP中原始文件的更改?

例如,我想刪除壓縮目錄內的特定文件,然後下載修改後的zip文件,以便該文件仍然存在於原始壓縮目錄中。

這是我的代碼到目前爲止。它工作正常,但問題是,該文件還原來壓縮目錄中刪除:

<?php 

$directoryPath = '/Users/Shared/SampleDirectory.zip'; 
$fileToDelete = 'SampleDirectory/samplefile.txt'; 

$zip = new ZipArchive(); 

if ($zip->open($directoryPath) === true) { 
    $zip->deleteName($fileToDelete); 
    $zip->close(); 
}  

header('Content-Description: File Transfer'); 
header('Content-Type: application/zip'); 
header('Content-Disposition: attachment; filename="' . basename('SampleDirectory.zip') . '"'); 
header('Content-Length: ' . filesize('SampleDirectory.zip'));; 
readfile('SampleDirectory.zip'); 

?> 

我如何能實現所需的功能?

回答

1

所有的zip函數都會改變zip文件的內容。使用PHP的copy()函數在臨時位置創建文件副本的最簡單方法,並對該文件進行更改。您可以使用tempnam()避免名稱衝突,並在完成後使用unlink()文件。

下面是一個例子:

$directoryPath = '/Users/Shared/SampleDirectory.zip'; 
$fileToDelete = 'SampleDirectory/samplefile.txt'; 

$temp = tempnam('/tmp'); 
copy($directoryPath, $temp); 

$zip = new ZipArchive(); 

if ($zip->open($temp) === true) { 
$zip->deleteName($fileToDelete); 
$zip->close(); 
}  

header('Content-Description: File Transfer'); 
header('Content-Type: application/zip'); 
header('Content-Disposition: attachment; filename="'.basename('SampleDirectory.zip').'"'); 
header('Content-Length: ' . filesize($temp)); 
readfile($temp); 

unlink($temp); 

警告:未經測試的代碼,請確保您有備份的文件。