views:

294

answers:

3

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

A: 

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.

Emil Vikström
I need to write the zip file in such a way that a subsequent unzip -p outputs the files in the correct order. Is that possible using the technique you describe with reading the zipfile into an array and sorting?
Peter Lindqvist
A: 

The sort order of unzipped files (or any files on the file system) depends on the 'client' you use to view the files. The ls command on a *nix system will display the files ordered by name as the default. If you are using some form of file manager application (or unzipper) you will be able to choose the sorting. Predefined sorting on an archive does not make much sense to me.

fmk_ca
I'm not talking about files in the file system, only files within zip archives. And while it may not make sense to you, it does to me. I cannot change the sorting in the "client" side. I have to write a file with the files in the correct order.
Peter Lindqvist
+2  A: 

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();
Peter Lindqvist