Search code examples
phpzip

PHP ZipArchive - Search Entry Contents for String


I would like to search files for a given string within a zipped folder.

I can currently get a list of my zipped files doing the following:

$zip = new ZipArchive;
$res = $zip->open("./test.zip");
var_dump($res);
for( $i = 0; $i < $zip->numFiles; $i++ ){
    $stat = $zip->statIndex( $i );
    var_dump($stat['name']);
}
$zip->close();

I have been reviewing the solutions found here. The only solution that seems to touch on what I need is both procedural and has a comment noting the following:

zip_entry_read reads only 1024 bytes from file by default.. so contents is not full contents of the file, but only first 1024 bytes

Is there a (OOP) way to search the entirety of my entries for a string before I choose to unzip my folder? Additionally, if I wanted to display the full contents of a zipped file would it need to be unzipped first? Lastly, if the full contents cannot be displayed without unzipping, is there a way to extract a single file from a zipped folder?


Solution

  • You can use ZipArchive::getFromName() or ZipArchive::getFromIndex() to read the zipped file contents.

    $zip = new ZipArchive;
    $res = $zip->open("./test.zip");
    for( $i = 0; $i < $zip->numFiles; $i++ ){
        var_dump($zip->getFromIndex($i));
    }
    $zip->close();