I have seen the ZipArchive class in PHP which lets you read zip files. But I'm wondering if there is a way to iterate though its content without extracting the file first
Asked
Active
Viewed 4.8k times
4 Answers
77
As found as a comment on http://www.php.net/ziparchive:
The following code can be used to get a list of all the file names in a zip file.
<?php $za = new ZipArchive(); $za->open('theZip.zip'); for( $i = 0; $i < $za->numFiles; $i++ ){ $stat = $za->statIndex( $i ); print_r( basename( $stat['name'] ) . PHP_EOL ); } ?>

deceze
- 510,633
- 85
- 743
- 889
-
Thanks for the answer. I must have missed the numFiles field when looking through ZipArchive documentation. – Roman Mar 22 '12 at 08:13
-
16
-
@flu: Just my thought right now. Looks even worse than Plain Old PHP without classes. – Sebastian Mach Mar 11 '15 at 08:46
-
18
http://www.php.net/manual/en/function.zip-entry-read.php
<?php
$zip = zip_open("test.zip");
if (is_resource($zip))
{
while ($zip_entry = zip_read($zip))
{
echo "<p>";
echo "Name: " . zip_entry_name($zip_entry) . "<br />";
if (zip_entry_open($zip, $zip_entry))
{
echo "File Contents:<br/>";
$contents = zip_entry_read($zip_entry);
echo "$contents<br />";
zip_entry_close($zip_entry);
}
echo "</p>";
}
zip_close($zip);
}
?>
-
2zip_entry_read reads only 1024 bytes from file by default.. so contents is not full contents of the file, but only first 1024 bytes.. – Scholtz Oct 21 '19 at 21:31
-
5
0
I solved the problem like this.
$zip = new \ZipArchive();
$zip->open(storage_path('app/'.$request->vrfile));
$name = '';
//looped through the zip files and got each index name of the files
//since I only wanted the first name which is the folder name I break the loop
//after updating the variable $name with the index name and that's it
for( $i = 0; $i < $zip->numFiles; $i++ ){
$filename = $zip->getNameIndex($i);
var_dump($filename);
$name = $filename;
if ($i == 1){
break;
}
}
var_dump($name);

Uwe Keim
- 39,551
- 56
- 175
- 291

Marvin Collins
- 379
- 6
- 14
-8
Repeated Question. Search before posting. PHP library that can list contents of zip / rar files
<?php
$rar_file = rar_open('example.rar') or die("Can't open Rar archive");
$entries = rar_list($rar_file);
foreach ($entries as $entry) {
echo 'Filename: ' . $entry->getName() . "\n";
echo 'Packed size: ' . $entry->getPackedSize() . "\n";
echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";
$entry->extract('/dir/extract/to/');
}
rar_close($rar_file);
?>
-
16lol so you scold for a duplicate question then subsidize the behavior with an answer. Nice :) – Mar 22 '12 at 06:42
-
16vote to close duplicate question instead of duplicating answers - you should read the Bible before preaching it. – Repox Mar 22 '12 at 06:51