Search code examples
phpziptarphargzip

Get total number of files inside a tar.gz file using php


I'm noob with php, but in a project I want to count the number of files that have a tar.gz, I know how to count files for a zip, but my question is: can I (with a php function) count how many files there are in a tar.gz file.?

With php I can count the number of files inside a zip file with a code like this

$zip = new ZipArchive(); 
if($zip->open("/path/to/the/zip")===true)
{
    print $zip->numFiles;
}
else
{
    print "cant open zip file";
}

but for tgz files can I do some similar (without use exec function)?

thanks :)


Thanks to Kkinsey I have an answer (with a few modification of his code). the final code will be

<?php

$archive = new PharData('/route/to/file.tar.gz');
$i=0;
foreach($archive as $file) 
{
    $i+=1;
}
print $i;
?>

thank you @Kkinsey


Solution

  • Try PharData:

    // Example: list files
    $archive = new PharData('/some/file.tar.gz');
    foreach($archive as $file) {
            echo "$file\n";
    }