PHP write binary response

2019-02-16 07:16发布

问题:

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

回答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;


回答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";
?>


回答3:

Usually, I use chr();

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

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



回答4:

You probably want the pack function -- it gives you a decent amount of control over how you want your values structured as well, i.e., 16 bits or 32 bits at a time, little-endian versus big-endian, etc.