Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jlucia's avatar

PHP ZipArchive to zip files with no folders.

I have 6 csv files inside of /storage/exports. I need to be able to zip up all 6 files into an archive so when unzipped, the 6 files are there, with no parent folder. From what I have tried, when I loop through the 6 files, the ZipArchive creates a folder with the name of the archive, regardless if I tell it to not use any path. If I simply loop through 1 file, it goes into the zip as expected with no other folders. I am thinking this may be a limitation of that class.

Maybe some of you have needed to do this and would have a suggestion. The backup plan is to run a script to do it in linux, but a pure PHP option would be perfect for the app it will be part of.

Here is what I have so far.

$destination = storage_path('exports/');

$archive = $destination.'archive.zip';

// If using just file1.csv, it works, when I loop through all, I get a folder.

$files = [
    'file1.csv', 'file2.csv', 'file3.csv', 'file4.csv', 'file5.csv', 'file6.csv'
];

$zip = new ZipArchive;

if(file_exists($archive)) {
    $zip->open($archive, ZipArchive::OVERWRITE); 
} else {
    $zip->open($archive, ZipArchive::CREATE);
}

foreach($files as $file) {
    $zip->addFile($destination.$file, $file);
}

$zip->close();

echo "Done";

Thanks for any suggestions out there. JL

0 likes
1 reply

Please or to participate in this conversation.