Reputation: 36205
I am working on a project where I need to send variables to a PHP script as a post.
The C# calls a few methods to set string variables which I then need to post to a PHP script so that the PHP script can use the data from the variables.
How can I go about doing this, I have tried google but they all look a bit complex and also how to get the data back from PHP which is difficult to work out where the post start and finishes in the example.
All I need to know is how to post the data to the script and not for the C# to then read what the PHP script has done.
Thanks for any help you can provide.
UPDATE I don't think I have explained myself very well for what I want to achieve.
What the purpose of this is to send data which will be in a string format to a PHP page via a post. I then want to load the script into the users web browser and they will be able to see the php page and when they submit the form from the php page it can use the information from the post that was sent to it.
Below is a step by step of what will happen
Hope this makes a bit more sense, that's why I was saying I didn't want C# to return what the PHP script was doing as the user needs to be able to work with the php page.
Upvotes: 0
Views: 3296
Reputation: 5688
Check this out :
public static string Post(string service, IDictionary<string, string> objects)
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(ServiceAdress+service+".php");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
StringBuilder b= new StringBuilder();
foreach(KeyValuePair<string,string> o in objects)
b.Append(HttpUtility.UrlEncode(o.Key)).Append("=").Append(HttpUtility.UrlEncode(o.Value??"")).Append("&");
if (PHPSESSID != null)
b.Append("PHPSESSID=").Append(PHPSESSID).Append('&');
string postData = b.ToString(0, b.Length - 1);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode != HttpStatusCode.OK)
return null;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
Upvotes: 1