Thursday 5 March 2009

Checking whether an entry in a zip archive is a file or a directory with PHP

When processing .zip files with PHP, a common problem is differentiating between files and directories inside the archive. A simple code like this shows what the zip extension returns for each entry:

<?php
$zip = zip_open('foo.zip');
while($entry = zip_read($zip)) {
$entry_name = zip_entry_name($entry);
echo 'name: ',$entry_name,PHP_EOL;
}


After having a closer look at the output, it becomes obvious that directory entries end in a trailing slash, and as such, we'll obviously do something like this:

<?php $zip = zip_open('foo.zip'); while($entry = zip_read($zip)) { $entry_name = zip_entry_name($entry); echo 'name: ',$entry_name,PHP_EOL; if('/' === substr($entry_name,-1)) { echo 'is a file',PHP_EOL; } else { echo 'is a directory',PHP_EOL; } }

Easy huh? :-)

No comments:

Post a Comment