PHP write binary response

godzcheater picture godzcheater · Jun 13, 2012 · Viewed 16.3k times · Source

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();

Answer

Andy Jones picture Andy Jones · Jun 13, 2012

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;