PHP8 returning ZipArchive getStream from a function makes the containing zip archive to be closed

149 Views Asked by At
private function getFilePointer($file)
{
    $pathInfo = pathinfo($file);
    
    $zip = new ZipArchive();
    if (($res = $zip->open($file)) !== true) {
        throw new Exception("error");
    }
    
    $fileName = preg_replace('/\d+/', '', str_replace('.zip', '.csv', $pathInfo['basename']));
    
    if (!($stream = $zip->getStream($fileName))) {
        throw new Exception("error");
    }
    
    return $stream;
}

If the following function is used to get the zip stream and using it in $row = fgetcsv($stream) it produces an error

PHP Error[2]: fgetcsv(): Zip stream error: Containing zip archive was closed

If using $zip->getStream($fileName) at the same function as you're trying to read with $row = fgetcsv($stream) then it doesn't throw an error.

It seems this behavior has changed from php7.4, but I couldn't find any documentation about it.

Does anyone know how to solve this issue, so the stream could be returned from a function and still be used?

1

There are 1 best solutions below

1
user133957 On

Looks like a garbage collection issue, can be solved using

static $zip = new ZipArchive();

you can also do:

return [ $stream, $zip ];

if you need it to be reentrant