Using the zip:// wrapper for an archive with a single file whose name is unknown

2.3k Views Asked by At

PHP allows to read ZIP files on-the-fly with the zip:// wrapper:

$fp = fopen ('zip://archive.zip#dir/file.txt', 'rb');

All good, when you know the compressed file name. This is not my case: my app has to deal with ZIP archives containing a single file, whose name is unknown before opening the archive.

Is there an option to tell the wrapper to open the first file in the archive, without the file name?

I know I can use ZipArchive or Zip Functions, I'd just like to keep it simple and use the stream wrapper if possible.

1

There are 1 best solutions below

0
On BEST ANSWER

I found the answer to my question after digging through the source code of the wrapper.

There is currently no way to open an archive with the wrapper without providing a file name.


A solution involves using both the wrapper and ZipArchive:

$path = '/path/to/archive.zip';

$zip = new \ZipArchive();

if ($zip->open($path) === true) {
    if ($zip->numFiles === 1) {
        $compressedFileName = $zip->statIndex(0)['name'];
        $zipPath = 'zip://' . $path . '#' . $compressedFileName;

        $fp = fopen($zipPath, 'rb');
        // ...
    }
}