Search code examples
phpphp-ziparchiveunlink

PHP unlink() files after it is added to ZipArchive


I am adding multiple files to a ZipArchive each file has a unique name.

Controller:

$zip = new ZipArchive();
$zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$filesToClose = $this->advancedService->addFiles($files, $zip);
$zip->close();

foreach ($filesToClose as $file) {
    fclose($file);
    unlink(stream_get_meta_data($file)['uri']);
}
// return response

Service:

// addFiles function
foreach ($files as $file) {
    $fileName = 'FILE_'.$file->getId().'.'.$file->getExtension();

    $tempFile = tmpfile();
    $content = file_get_contents('uriFromSdk');
    fwrite($tempFile, $content);
    $zipArchive->addFile(stream_get_meta_data($tempFile)['uri'], $fileName);

    $filesToClose[] = $tempFile;
}

return $filesToClose;

In controller I get this error:

stream_get_meta_data(): supplied resource is not a valid stream resource

The main problem is I can not close or delete any file before $zip->close(), How can I unlink the files from the server ?

Keep in mind fclose() doesn't throw this error, only the stream_get_meta_data().

Thanks.


Solution

  • Reverse order of fclose and unlink. First unlink then fclose. stream_get_meta_data requires an active stream.

    Returns information about an existing stream.

    foreach ($filesToClose as $file) {
        unlink(stream_get_meta_data($file)['uri']);
        fclose($file);
    }