Search code examples
phpbinarypackunpack

Unpacking binary data in PHP


I'm using a third party API that allows me to upload an image via a POST request and the parameter is required to be in binary format e.g. [137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,3,...]

I tried using the unpack() function and got the binary data to upload but when I try to view it on the upload server I only got a blank image BUT the image size is correct. So I think the data is there I'm just doing something wrong when unpacking.

        if(!$fp = fopen ($image_url, 'rb')) return 0;
        /* Read bytes from the top of the file */
        if(!$data = fread ($fp, filesize($image_path))) return 0;

        /* Unpack  data */
        $data = unpack ('C*', $data);
        //$data value: Array ( [1] => 137 [2] => 80 [3] => 78 [4] => 71 [5] => 13....

To test if it will convert back to the image correctly I use the pack() function like so:

        $bin = pack('C*', ...$data);
        header('Content-type: image/png');
        header('Content-Disposition: inline; filename="test_image"');
        header('Content-Transfer-Encoding: binary');
        echo $bin;
        exit();

So this will output a png file that is blank but has the same exact size as the original image. Is there are a way to fix the unpack function so that it will convert back correctly? I have no control on how to display it since it's in the third party API, so I can only correct it on the first code block.


Solution

  • I've tinkered a bit with what you're doing and this works for me:

    $data = file_get_contents('test.png');
    $u    = unpack('C*', $data);
    $bin  = pack('C*', ...$u);
    
    header('Content-type: image/png');
    echo $bin;
    exit();
    

    My assumption would be that your fopen and fread isn't returning what you're expecting.