2

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?

Rasmus Søborg
  • 3,597
  • 4
  • 29
  • 46
Diego Saa
  • 1,426
  • 1
  • 13
  • 23

2 Answers2

1

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);
?>
Community
  • 1
  • 1
George
  • 367
  • 1
  • 10
  • Thanks, but I would need $file... My problem is that I can't write in the file system. The original zippend file is on a different SFTP server. I'm able to get the contents of it into a variable, but, I'm not able to write to the file system... – Diego Saa Apr 30 '13 at 20:05
  • Yes, you would need `string $filename`. I am not sure if this is possible. Take a look [here](http://stackoverflow.com/questions/7391969/in-memory-download-and-extract-zip-archive). You might want to ask your Server Admin for privileges, or use a language besides php. – George Apr 30 '13 at 20:13
0

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.

Ariel Ruiz
  • 163
  • 2
  • 6