二进制模式写作

I am writing a php program to write a binary file (may be video or image files). I would like to make it as a web service and call it from another application like c#, mac etc.

My code is give below,

<?php
$fileChunk = $_POST["filechunk"];
$vodFolder = 'D:\\HYSA SVN\\Trunk\\workproducts\\source\\hysa_he\\web\\entertainment\\';
$vodFile = $vodFolder . "abcd.mov";
$fh = fopen($vodFile, 'ab');

flock ($fh, LOCK_EX);
$varsize = fwrite($fh, $fileChunk);
fclose($fh);
?>

But when I called the php web service from a c# code, the abcd.mov is creating in the location, but its size is only one kb. I suspects that, the writing in halted when a character ‘&’ found in the binary file. I read the php documentation and found that, fopen with binary mode ‘b’ will solve this issue? But it is not working. Can somebody help me ?

This is my c# code.

BinaryReader b = new BinaryReader(File.Open("d:\\image38kb.jpg", FileMode.Open));
int pos = 0;
int length = (int)b.BaseStream.Length;
byte[] bt = b.ReadBytes(length);

char[] ch = b.ReadChars(length);


HttpWebRequest request = null;
Uri uri = new Uri("http://d0327/streamtest.php");
request = (HttpWebRequest)WebRequest.Create(uri);
NetworkCredential obj = new NetworkCredential("shihab.kb",
            "India456*", "tvm");
request.Proxy.Credentials = obj;

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bt.Length;
using (Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes("filechunk=");
byte[] rv = new byte[bytes.Length + bt.Length];

System.Buffer.BlockCopy(bytes, 0, rv, 0, bytes.Length);
System.Buffer.BlockCopy(bt, 0, rv, bytes.Length, bt.Length);

writeStream.Write(rv, 0, bt.Length);
}

string result = string.Empty;
using (
HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
    using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
    {
    result = readStream.ReadToEnd();
    }
}
}

Well the problem is not in the fwrite part, that works fine.

However, POST requests in HTTP look like this:

POST /somepage.php HTTP/1.1
Content-Length: 34

variable1=blah&var2=something else

As you can see, variables are divided by ampersands (&) (as well as equal signs (=) for the key - value mapping)... So, even when using POST requests, ampersands are not safe characters.

To solve this, you could try another transfer method, for example, TCP/IP socket connection, or simply escape the ampersands with, say '\x26' (the ASCII value of ampersand) and escape all the backslashes (\) with '\x5C'... You'd have to edit the PHP code to parse these values.