Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control sort order of files in zip archive

Description

I'm interested in learning if there is any way to control sort order of files inside zip files using standard routines in PHP and/or Java.

I'm not primarily interested in using zip/unzip using shell_exec() or similar, but it can be of interest if it provides with an easy to read solution.

With sort order it's safe to assume it means date/time if no sort order is available within the zip file. I've not read the specs so I wouldn't know.

Example

Files

foo.txt
bar.txt
test.txt
newfile.txt

Let's assume that each file contains the name of the file (foo.txt => foo.txt)

Problem

I want to attach a sort order to the files so that when unpacked using unzip the files end up in the right order. This is important why? Because i use unzip -p to pipe the content of the zip file.

The order in which the files are added to the archive should not matter.

Result

Intended result (for the sake of this example (using unzip -p))

test.txt
foo.txt
newfile.txt
bar.txt

like image 701
Peter Lindqvist Avatar asked Jan 04 '10 08:01

Peter Lindqvist


2 Answers

It wasn't really that hard. I appears that the files index is related to the order in which the files are added to the archive and this controls the output of unzip -p since it seems to iterate files in the 0..n fashion.

Here is how to create a file that satisfies the conditions. (Well almost since i forgot the newlines in my txt files)

$files = array(
    'test.txt',
    'foo.txt',
    'newfile.txt',
    'bar.txt'
);

$outfile = 'testout.zip';
if (file_exists($outfile)) {
    unlink($outfile);
}
$o = new ZipArchive();
$o->open($outfile,ZipArchive::CREATE);
foreach($files as $key => $file) {
    $o->addFile($file);
}

$o->close();
like image 154
Peter Lindqvist Avatar answered Sep 30 '22 10:09

Peter Lindqvist


You can use the command zipinfo (or unzip -Z) to show files in the archive. man zipinfo also have examples on how to sort the output, but it can also be sorted in PHP if you read in the files in an array and sort the array.

like image 23
Emil Vikström Avatar answered Sep 30 '22 10:09

Emil Vikström