I have run into a bit of a problem when zipping files in PHP. I have a function which zips an array of files, these files are all in different directories. The function looks like :
function create_zip($files = array(),$destination = '',$overwrite = false,$add_to_db=true) {
print_r($files);
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
for($i=0;$i < count($files); $i++) {
//echo $files[$i].'<br>';
$zip->addFile($files[$i],$files[$i]);
}
$zip->close();
if(file_exists($destination)) {
// echo("Success");
if($add_to_db == true) { add_file($destination); }
return true;
} else {
//echo("Failed");
return false;
}
}
When a user downloads and extracts the zip the structure of files is like :
folder/folder2/file1.jpg
folder/file2.jpg
folder/folder2/folder3/file3.jpg
My question is, is it possible to have PHP place all the files in the root of the zip and ignore the given structure. So the extracted files would look like:
/file1.jpg
/file2.jpg
/file3.jpg
The only solution I could think of was moving all the files into a folder and then zipping this folder, but this seemed like overkill.
archive.php php $zip = new ZipArchive(); $zip->open('example. zip', ZipArchive::CREATE); $srcDir = "/home/sam/uploads/"; $files= scandir($srcDir); //var_dump($files); unset($files[0],$files[1]); foreach ($files as $file) { $zip->addFile("{$file}"); } $zip->close(); ?>
Here we use XAMPP to run a local web server. Place the php files along with the directory to be zipped in C:\xampp\htdocs(XAMPP is installed in C: drive in this case). In the browser, enter https://localhost/zip.php as the url and the file will be zipped. After this a new zip file is created named 'file'.
Specify just a filename (no path) for the 2nd parameter to addFile()
:
$zip->addFile( $files[$i], basename($files[$i]) );
https://www.php.net/manual/en/ziparchive.addfile.php
Be aware that if you attempt to add multiple files with the same basename (e.g. folder1/foo.jpg
and folder2/foo.jpg
), you'll overwrite the first one and only the second one will end up in the zip file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With