Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/28f173bf42aa052ed04bb6e8bb7a95ef to your computer and use it in GitHub Desktop.
Save code-boxx/28f173bf42aa052ed04bb6e8bb7a95ef to your computer and use it in GitHub Desktop.
PHP Read Zip Files

PHP READ ZIP FILES

https://code-boxx.com/read-zip-file-php/

NOTES

Please make sure that extension=zip is enabled in php.ini.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
// (A) OPEN ZIP FILE
$file = "test.zip";
$zip = new ZipArchive;
if ($zip->open($file, ZipArchive::RDONLY) !== true) {
exit("Failed to open $file");
}
// (B) LOOP THROUGH EVERY FILE & FOLDER - DISPLAY INFORMATION
$total = $zip->count();
for ($i=0; $i<$total; $i++) {
print_r($zip->statIndex($i));
}
// (C) CLOSE ZIP
$zip->close();
<?php
// (A) OPEN ZIP FILE
$file = "test.zip";
$zip = new ZipArchive;
if ($zip->open($file, ZipArchive::RDONLY) !== true) {
exit("Failed to open $file");
}
// (B) DIRECTLY READ FILE USING INDEX
$content = $zip->getFromIndex(0);
echo "$content<br>";
// (C) OR USE GET FROM FILE NAME
$content = $zip->getFromName("second.txt");
echo "$content<br>";
// (D) CLOSE ZIP
$zip->close();
<?php
// (A) OPEN ZIP FILE
$file = "test.zip";
$zip = zip_open($file);
if (is_numeric($zip) || $zip===false) {
exit("Failed to open $file");
}
// (B) READ FILES
while ($entry = zip_read($zip)) {
// (B1) GET FILE NAME & SIZE
$name = zip_entry_name($entry);
$size = zip_entry_filesize($entry);
echo "$name - $size bytes<br>";
// (B2) READ FILE DIRECTLY
if ($name == "first.txt") {
if (zip_entry_open($zip, $entry)) {
$contents = zip_entry_read($entry);
echo "$contents<br>";
zip_entry_close($entry);
} else { echo "Cannot open first.txt"; }
}
}
zip_close($zip);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment