0

I ran into a problem lately:

C# code:

string URI = "http://cannonrush.tk/UpdateLogFile.php";
string myParameters = "text=test123";

using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(URI, myParameters);
    Console.WriteLine(HtmlResult);   
}

PHP file:

<?php
if (isset($_GET['text'])) {
    $file = "LogFile.txt";
    $handle = fopen($file, 'a') or die('ERROR: Cannot write to file: ' . $file);
    date_default_timezone_set('Europe/Amsterdam');
    $data = '~ ' . date('l jS \of F Y h:i:s A') . '>> ' . $_GET['text'] . "\n\n";
    fwrite($handle, $data);
    fclose($handle);
    echo "SUCCESS";
} else {
    echo "ERROR: Access forbidden without text";
}
?>

Now, whenever I run the above C# code, I get this output printed:

ERROR: Access forbidden without text

I have tried numerous versions to post data from C# to php, but nothing seems to work.

Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
LetsCode
  • 82
  • 8
  • I don't know PHP, but the UploadString method uses POST and would put the string in the body, is it possible that PHP is expecting a GET and looking for a querystring? http://stackoverflow.com/questions/5415224/how-to-set-get-variable – Mike_G Oct 24 '14 at 21:08

2 Answers2

0

Change $_GET["text"] to $_POST["text"] in the php file, or use DownloadString() instead of UploadString() in your C# code.

HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
0

$_GET is only populated in GET requests, so UploadString will not work:

Uploads the specified string to the specified resource, using the POST method.

If you want to allow either verb, use $_REQUEST instead.

Tieson T.
  • 20,774
  • 6
  • 77
  • 92