2
votes

I have a PHP array, which contains bytes, and the actual bytes represent a ZIP file (which contains multiple files inside the ZIP).

This is returned from a third party API, so I have no choice but to work with this format.

So I'm trying to convert this into the ZIP file.

Example of byte array returned by API:

[bytes] => Array
            (
                [0] => 37
                [1] => 80
                [2] => 68
                [3] => 70
                [4] => 45
                [5] => 49
                [6] => -46
... continues to close to 20,000
)

I have tried simply getting the browser to return it by creating a complete byte string, and adapting browser headers... using:

foreach($bytes as $byte)
{
    $byteString .= $byte;
}
header("Content-type: application/zip"); 
header("Content-Disposition: inline; filename='test.zip'");
echo $byteString;

This does create a zip file, but it's invalid / corrupted.

I have also tried this which I found elsewhere on Stackoverflow:

$fp = fopen('/myfile.zip', 'wb+');

while(!empty($bytes)) {
     $byte1 = array_shift($bytes);
     $byte2 = array_shift($bytes);
     if(!$byte2) {
         $byte2 = 0;
     }
fwrite($fp, pack("n*", ($byte1 << 8) + $byte2)); 
}
close($fp);

But again, the ZIP is created, but it's invalid / corrupted.

Any pointers, most appreciated.

Thanks

1
it seems extremely likely your using this API wrong.user557846
"it seems extremely likely your using this API wrong." -- no, I wish I was thought! It's a custom API and this is indeed how it's been set up.rjbathgate

1 Answers

1
votes

With the help of an ascii table it's easy to decode the data you're receiving, and you will see that it starts with

%PDF

which means that the returned data is in PDF format, not zip. Zip files start with PK, the initials of the inventor of the format, the late Phil Katz.

As a general note, knowing about the common file type signatures is quite useful and can save you lots of time.