PHP write binary response

18,499

Solution 1

In PHP, strings and byte arrays are one and the same. Use pack to create a byte array (string) that you can then write. Once I realized that, life got easier.

$my_byte_array = pack("LL", 0x01000000, 0xFC030000);
$fp = fopen("somefile.txt", "w");
fwrite($fp, $my_byte_array);

// or just echo to stdout
echo $my_byte_array;

Solution 2

This is the same answer I posted to this, similar, question.

Assuming that array $binary is a previously constructed array bytes (like monochrome bitmap pixels in my case) that you want written to the disk in this exact order, the below code worked for me on an AMD 1055t running ubuntu server 10.04 LTS.

I iterated over every kind of answer I could find on the Net, checking the output (I used either shed or vi, like in this answer) to confirm the results.

<?php
$fp = fopen($base.".bin", "w");
$binout=Array();
for($idx=0; $idx < $stop; $idx=$idx+2 ){
    if( array_key_exists($idx,$binary) )
        fwrite($fp,pack( "n", $binary[$idx]<<8 | $binary[$idx+1]));
    else {
        echo "index $idx not found in array \$binary[], wtf?\n";
    }
}
fclose($fp);
echo "Filename $base.bin had ".filesize($base.".bin")." bytes written\n";
?>

Solution 3

Usually, I use chr();

echo chr(255); // Returns one byte, value 0xFF

http://php.net/manual/en/function.chr.php

Share:
18,499

Related videos on Youtube

godzcheater
Author by

godzcheater

Updated on September 14, 2022

Comments

  • godzcheater
    godzcheater about 1 year

    In php is there a way to write binary data to the response stream,
    like the equivalent of (c# asp)

    System.IO.BinaryWriter Binary = new System.IO.BinaryWriter(Response.OutputStream);
    Binary.Write((System.Int32)1);//01000000
    Binary.Write((System.Int32)1020);//FC030000
    Binary.Close();
    



    I would then like to be able read the response in a c# application, like

    System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("URI");
    System.IO.BinaryReader Binary = new System.IO.BinaryReader(Request.GetResponse().GetResponseStream());
    System.Int32 i = Binary.ReadInt32();//1
    i = Binary.ReadInt32();//1020
    Binary.Close();
    
  • Krista K
    Krista K about 10 years
    +1 for answer that helped me. I'm adding what worked for me below as another answer.
  • Mikko Rantalainen
    Mikko Rantalainen almost 3 years
    I prefer to use print() instead of echo because it's more like a function. Neither is technically a real function, though. The documentation calls them as "language constructs". It's also technically possible to do fopen("php://output") if you need file descriptor for output. For details, see php.net/manual/en/wrappers.php.php