Reputation: 2512
I have a compressed directory which contains some files and subdirectories. What I want to achieve is to modify the content of the compressed directory and then download the modified zip file, so that the changes are not altered inside the original zip file.
For example, I want to delete a specific file inside the compressed directory and then download the modified zip file, so that the file still exists in the original compressed directory.
Here is my code so far. It works fine, but the problem is that the file is also deleted inside the original compressed directory :
<?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');
?>
How can I achieve the desired functionality?
Upvotes: 0
Views: 59
Reputation: 4025
All zip functions change the content of the zip file. The easiest way it to create a copy of the file at a temporary location using PHP's copy() function and operate the changes on that file. You can use tempnam() to avoid name conflicts and unlink() the file after you're done.
Here's an example:
$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);
Warning: untested code, make sure you have backups to the files.
Upvotes: 1