tags:

views:

38

answers:

3

I am building a console application that gathers some data and then sends it to a php page through a POST request. This is my C# code:

HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("http://localhost/log.php");
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
string PostData = "data=" + UserOutput;
Request.ContentLength = PostData.Length;

StreamWriter stOut = new StreamWriter(Request.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(PostData);
stOut.Close();

And the PHP page (log.php):

<?php

file_put_contents('log.txt', $_POST['data']);

?>

Note I am only using file_put_contents to test if everything works OK, it is not what I want to end up doing.

The length of the post data to send is over 2,000 characters long, and the correct content length is returned by Request.ContentLength = PostData.Length;, so that's not the problem. But whenever I try this it is only sending the first 46 characters of my POST data.

I do have to admit at this point that I copied most of the code, as I am not very experienced in C#.

Any help would be great, thanks.

+3  A: 

Is the 47th character "&" by any chance? You've claimed that your data is URL-encoded, but you haven't done any URL-encoding in the code you've provided. If there's an "&" that would indicate to PHP that it was about to accept a new form parameter...

One way to verify this (apart from using HttpUtility.UrlEncode) would be to use Fiddler or Wireshark to see what's actually going on at the network level.

Jon Skeet
Aha, I never actually thought of that. That is the problem and I'll make sure to UrlEncode it from now on. Thanks :)
Kratz
A: 

The Close() should handle it, but you may want to try a .Flush() just before that.

James Curran
A: 

If you're only sending one big blob of data, it would be a better strategy to omit the Content-type header and make PostData == UserOutput.

You could then save it with

$s = fopen("php://input", "r");
file_put_contents('log.txt', $s);
Artefacto