I want to post data from C#(Windows Forms Application) to PHP using $_POST, but getting empty value when checking with echo/var_dump, while in Locals windows of VS, showing the value of ResponseStream with data that has been posted. I don't know if the problem is in C# method or PHP script or anything else.
From Pass data from C# to PHP, and some more questions, in my case, I have applied it as the following.
PHP script (post.php):
<?php
// *** Use $_GET, the echo works when testing parameters from browser's address bar, but GET method in C# will fail.
//if(isset($_POST['data'])){
//if($_SERVER['REQUEST_METHOD'] == "POST"){
$data = $_POST['data'];
echo "Hello, ";
echo $data;
//}
?>
<!-- for debug purpose -->
<pre>
<?php
var_dump($_POST);
//print_r($_POST);
var_dump($_REQUEST);
?>
</pre>
C# method:
public string SendPost(string url, string postData)
{
string webpageContent = string.Empty;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0x30 | 0xc0 | 0x300 | 0xc00);
// https://stackoverflow.com/questions/12506575/how-to-ignore-the-certificate-check-when-ssl
ServicePointManager.ServerCertificateValidationCallback +=
delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true; // **** Always accept
};
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
using (Stream webpageStream = webRequest.GetRequestStream())
{
webpageStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
webpageContent = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
MessageBox.Show("Data has been posted.");
return webpageContent;
}
Here is how I call method:
String pData = "TestString";
SendPost("https://websites/post.php", String.Format("data={0}", pData));
Results
In Locals windows, the return value of "webpageContent":
Hello, TestString
From browser, "https://websites/post.php":
Hello,
How to keep/display/use the value received from C# in PHP?