I am trying to zip all files and folder within a folder The structure looks like so:
storage/app/3 - folder 1 -file 1 -file 2 - folder 2 -file 3
When I run the zip script I want the zip to be 3.zip with all the folders and files in the next level However I always end up with:
3.zip - 3 - folder 1 -file 1 -file 2 - folder 2 -file 3
Where I want:
3.zip - folder 1 -file 1 -file 2 - folder 2 -file 3
The code works on my Linux servers, but on IIS and windows I get the additional level.
This is my code:
$rootPath = public_path() .'/storage/app/' . $request->course_id . '/'; $zip = new ZipArchive(); $zip->open(public_path() .'/storage/app/' . $request->course_id . '/' . $request->course_id . '.zip', (ZipArchive::CREATE | ZipArchive::OVERWRITE)); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY ); foreach($files as $name => $file) { if (!$file->isDir() AND (strpos($name, $request->course_id.'.zip') === FALSE)){ $zip->addFile($file, str_replace("C:sitescnnect-portalpublic/storage/app/","", $file)); } }
I have tried to exclude the file from the loop by saying ‘if $name == $request->course_id’ skip this but that doesnt work because I dont see $name ever being just the folder name.
Advertisement
Answer
This will extracts the filename from the path.
$zip->addFile($file,basename($file));
And another guess would be that you need to include course_id
here also:
foreach($files as $name => $file) { if (!$file->isDir() AND (strpos($name, $request->course_id.'.zip') === FALSE)){ $zip->addFile($file, str_replace("C:sitescnnect-portalpublic/storage/app/3","", $file)); } }