Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In memory download and extract zip archive

Tags:

php

zip

unzip

I would like to download a zip archive and unzip it in memory using PHP.

This is what I have today (and it's just too much file-handling for me :) ):

// download the data file from the real page
copy("http://www.curriculummagic.com/AdvancedBalloons.kmz", "./data/zip.kmz");

// unzip it
$zip = new ZipArchive;
$res = $zip->open('./data/zip.kmz');
if ($res === TRUE) {
    $zip->extractTo('./data');
    $zip->close();
}

// use the unzipped files...
like image 363
dacwe Avatar asked Sep 12 '11 18:09

dacwe


3 Answers

Warning: This cannot be done in memory — ZipArchive cannot work with "memory mapped files".

You can obtain the data of a file inside a zip-file into a variable (memory) with file_get_contentsDocs as it supports the zip:// Stream wrapper Docs:

$zipFile = './data/zip.kmz';     # path of zip-file
$fileInZip = 'test.txt';         # name the file to obtain

# read the file's data:
$path = sprintf('zip://%s#%s', $zipFile, $fileInZip);
$fileData = file_get_contents($path);

You can only access local files with zip:// or via ZipArchive. For that you can first copy the contents to a temporary file and work with it:

$zip = 'http://www.curriculummagic.com/AdvancedBalloons.kmz';
$file = 'doc.kml';

$ext = pathinfo($zip, PATHINFO_EXTENSION);
$temp = tempnam(sys_get_temp_dir(), $ext);
copy($zip, $temp);
$data = file_get_contents("zip://$temp#$file");
unlink($temp);
like image 98
hakre Avatar answered Oct 08 '22 12:10

hakre


As easy as:

$zipFile = "test.zip";
$fileInsideZip = "somefile.txt";
$content = file_get_contents("zip://$zipFile#$fileInsideZip");
like image 25
Pedro Lobito Avatar answered Oct 08 '22 11:10

Pedro Lobito


Old subject but still relevant since I asked myself the same question, without finding an answer.

I ended up writing this function which returns an array containing the name of each file contained in the archive, as well as the decompressed contents of that file:

function GetZipContent(String $body_containing_zip_file) {

    $sectors = explode("\x50\x4b\x01\x02", $data);
    array_pop($sectors);
    $files = explode("\x50\x4b\x03\x04", implode("\x50\x4b\x01\x02", $sectors));
    array_shift($files);

    $result = array();
    foreach($files as $file) {
        $header = unpack("vversion/vflag/vmethod/vmodification_time/vmodification_date/Vcrc/Vcompressed_size/Vuncompressed_size/vfilename_length/vextrafield_length", $file);
        array_push($result, [
            'filename' => substr($file, 26, $header['filename_length']),
            'content' => gzinflate(substr($file, 26 + $header['filename_length'], -12))
        ]);
    }
    
    return $result;
}

Hope this is useful ...

like image 37
Olivier JC Avatar answered Oct 08 '22 11:10

Olivier JC