4

In a symfony Controller I have a file (UploadedFile object) as a variable.

I want to open this "variable" with php ZipArchive, and extract it. But the open() methods is expecting a string, which is the filename in the filesystem. Is there any way to process the file with the ZipArchive and without writing the file variable to the FS?

Qonq
  • 57
  • 6

3 Answers3

3

You can use tmpfile() to create a temporary file, write to it and then use it in the zip. Example:

<?php

$zip = new ZipArchive();
$zip->open(__DIR__ . '/zipfile.zip', ZipArchive::CREATE);

$fp = tmpfile();
fwrite($fp, 'Test');
$filename = stream_get_meta_data($fp)['uri'];

$zip->addFile($filename, 'filename.txt');
$zip->close();

fclose($fp);
lsouza
  • 2,448
  • 4
  • 26
  • 39
2

Little improve:

$zipContent; // in this variable could be ZIP, DOCX, XLSX etc.

$fp = tmpfile();
fwrite($fp, $zipContent);
$stream = stream_get_meta_data($fp);
$filename = $stream['uri'];

$zip = new ZipArchive();
$zip->open($filename);
// profit!
$zip->close();
fclose($fp);

Just make no sense to create "zipfile.zip" and add file inside, because we already have a variable.

Levsha
  • 455
  • 3
  • 18
1

Check out this answer at https://stackoverflow.com/a/53902626/859837

There is a way to create a file which resides in memory only.

Francisco Luz
  • 2,775
  • 2
  • 25
  • 35