user1513196 user1513196 - 11 months ago 108
PHP Question

PHP Array of Bytes to Zip File

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=''");
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('/', 'wb+');

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

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

Any pointers, most appreciated.


fvu fvu
Answer Source

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


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.