Ne-Lexa / php-zip

PhpZip is a php-library for extended work with ZIP-archives.
MIT License
491 stars 60 forks source link

Empty PSR-7 ZIP-File in body stream #91

Closed odan closed 2 years ago

odan commented 2 years ago
Q A
Library version(s) affected: 4.0.2
PHP version(s): 8.1.6
OS (with bit depth): Windows 10 64-bit

Description

When I try to output a ZIP-File as PSR-7 response, the ZIP file is valid, but contains no files. I use the existing nyholm/psr7 response object.

How to reproduce

$zipFilename = sprintf('%s.zip', tempnam(sys_get_temp_dir(), 'test'));

$zip = new \PhpZip\ZipFile();
$zip = $zip->addFromString('file.txt', 'File content');
$zip = $zip->saveAsFile($zipFilename);
$zip->close();

$realContent = file_get_contents($zipFilename);

// $response = new \Nyholm\Psr7\Response();
$response = $zip->outputAsPsr7Response($response, 'test.zip');

$bodyContent = (string)$response->getBody();

echo strlen($realContent) . "\n";  // 126 bytes
echo strlen($bodyContent) . "\n"; // 22 bytes

if ($bodyContent !== $realContent) {
    echo 'Invalid ZIP content';
    exit;
}

return $response;

Possible Solution

Additional context

Ne-Lexa commented 2 years ago

@odan you use the PSR7 response incorrectly.

<?php

require __DIR__ . '/vendor/autoload.php';

try {
    $zip = new \PhpZip\ZipFile();
    $zip = $zip->addFromString('file.txt', 'File content');
    $response = $zip->outputAsPsr7Response(new \Nyholm\Psr7\Response(), 'test.zip');

    $bodyContent = (string)$response->getBody();

    echo strlen($bodyContent) . "\n"; // 126 bytes
} finally {
    $zip->close();
}
odan commented 2 years ago

Hi @Ne-Lexa Thank's for the quick answer.

It was not how I use the response object. The actual issue was to invoke the $zip->close(); method before calling the outputAsPsr7Response method. Without closing the file, the response object is valid now. Thanks.