2

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

2
  • it seems extremely likely your using this API wrong. Commented Aug 24, 2016 at 0:48
  • "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. Commented Aug 24, 2016 at 1:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Despite API docs clearly stating it would return a ZIP, indeed it's a PDF. Using the second code example, and changing the file extension to .pdf, I end up with a valid PDF. The contents of the PDF is however blank, but it has meta data such as orientation and size, so actual 'contents' missing must be issue with actual byte data. Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.