Search code examples
phpfile-uploadziparchivephp-ziparchive

Help with php function zip_open


It's now 5am, and as much as I try to research, I can't find much information on this function set. Here's the code I have (shortened slightly):

<?php
$source = $_FILES["restore_file"]["tmp_name"];
$zip = zip_open($source);
while ($zip_entry = zip_read($zip)) {
    echo zip_entry_name($zip_entry).'\n';
}
?>

which when I upload my example zip out puts:

example/
example/index.php
example/file1.csv
example/file2.csv
example/file3.csv
etc.

I need to know how to access the contents of those files though, and also be able to specify which file I am accessing exactly. For example, before going through the csv files, I need to check a php variable in the index.php file of the archive, to make sure it is correct.

Is using the ZipArchive class a better idea instead of the zip functions perhaps? I was under the impression though that using the zip functions would be better as it can access the files on the fly (without having to transfer the files to a new directory).


Solution

  • Use ZipArchive::getFromName(). Example from the PHP manual adapted to your case:

    $zip = new ZipArchive();
    if ($zip->open($_FILES["restore_file"]["tmp_name"]) === true) {
        echo $zip->getFromName('example/index.php');
        $zip->close();
    } else {
        echo 'failed';
    }