Search code examples
phpphp-ziparchive

How to add only relative path with PHP ZipArchive::addPattern?


As simple as the title:

$zipFileName = $folderName . DIRECTORY_SEPARATOR . strtolower(sprintf('bundle_%s.zip', date('F_Y', strtotime('last month'))));

$zip = new \ZipArchive();
if ($zip->open($zipFileName, \ZIPARCHIVE::CREATE )!==TRUE) {
    throw new \Exception("cannot open <$zipFileName>\n", 500);
}

$zip->addPattern('/\.csv$/', $folderName, ['remove_path' => $folderName]);
$zip->close();

This is creating a zip file with the path as the absolute path on the machine:

So I'm opening the resulting zip and having:

/tmp/bundle/file1.csv
/tmp/bundle/file2.csv
/tmp/bundle/file3.csv

But, I would like to get:

file1.csv
file2.csv
file3.csv

Not sure what else to try?


Solution

  •     $zip         = new \ZipArchive();
        if($zip->open($zipFullPath, \ZIPARCHIVE::CREATE) !== TRUE)
        {
            throw new \Exception("Cannot open <$zipFullPath>\n", 500);
        }
        foreach(glob($folderName . DIRECTORY_SEPARATOR . '*') as $file)
        {
            $zip->addFile($file, basename($file));
        }
        $zip->close();
    

    This is how I ended up doing it. No luck with addPattern function.