Diego Saa
Diego Saa

Reputation: 1456

Unzipping to a variable

I need to process the contents of a zipped file, but I can't change the permissions on the server where my program will be hosted.

This means that I can't download the zip file to the server, so I need to read the contents of the file into a variable without writing it to the file system.

Can I grab the string contents of such variable and get the unzipped contents into a new variable?

So far, I've looked into using the zip php extension, and the pclzip library, but both need to use actual files.

This is what I want to do in pseudo code:

$contentsOfMyZipFile = ZipFileToString();
$myUnzippedContents = libUnzip($contentsOfMyZipFile);

Any ideas?

Upvotes: 2

Views: 1641

Answers (2)

Ariel Ruiz
Ariel Ruiz

Reputation: 179

I use this in my project:

 function unzip_file( $data ) {
    //save in tmp zip data
    $zipname = "/tmp/file_xxx.zip";

    $handle = fopen($zipname, "w");
    fwrite($handle, $data);
    fclose($handle);

    //then open and read it.
    $open = zip_open($zipname);

    if (is_numeric($open)) {
        echo "Zip Open Error #: $open";
    } else {
        while ($zip = zip_read($open)) {
            zip_entry_open($zip);
            $text = zip_entry_read($zip, zip_entry_filesize($zip));
            zip_entry_close($zip);
        }
    }
    /*delete tmp file and return variable with data(in this case plaintext)*/
    unlink($zipname);
    return $text;
 }

I hope it helps you.

Upvotes: 0

George
George

Reputation: 357

Look at this example.

<?php
$open = zip_open($file);

if (is_numeric($open)) {
    echo "Zip Open Error #: $open";
} else {
while($zip = zip_read($open)) {
    zip_entry_open($zip);
    $text = zip_entry_read($zip , zip_entry_filesize($zip));
    zip_entry_close($zip);
}
print_r($text);
?>

Upvotes: 1

Related Questions