Qonq
Qonq

Reputation: 57

use PHP ZipArchive with file as variable

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?

Upvotes: 4

Views: 2691

Answers (3)

Francisco Luz
Francisco Luz

Reputation: 2943

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

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

Upvotes: 1

Levsha
Levsha

Reputation: 494

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.

Upvotes: 2

lsouza
lsouza

Reputation: 2488

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);

Upvotes: 3

Related Questions