Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a .tar.gz file with PHP?

Tags:

php

zip

tar

I am building a system for people to upload .tar (and .tar.gz, .tar.bz2, .zip, etc) files in PHP. Uploading the files is fine, but I would like to list files contained in the archive after it has been uploaded.

Can someone recommend a good PHP library that can read file archives?

I found File_Archive on Pear but it hasn't been updated in a few years. ZipArchive works great for .zip files, but I need something that can handle more file types.

update I'm running on RHEL6, PHP 5.2, and Apache 2.2.

like image 748
Michael Avatar asked Feb 02 '11 19:02

Michael


1 Answers

You can do this with the PharData class:

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

This even works with the phar:// stream wrapper:

$list = scandir('phar:///some/file.tar.gz');
$fd = fopen('phar:///some/file.tar.gz/some/file/in/the/archive', 'r');
$contents = file_get_contents('phar:///some/file.tar.gz/some/file/in/the/archive');

If you don't have Phar, check the PHP-only implementation, or the pecl extension.

like image 54
Arnaud Le Blanc Avatar answered Oct 22 '22 15:10

Arnaud Le Blanc