Archive

Archive for March, 2011

How to call a PHP Script from ASP.NET C# and View Its response?

March 7, 2011 17 comments

Hi guys,
I was wondering on net abt , how to call a PHP Script from ASP.NET C#, then found a simple solution.
Actually, Its nothing but calling any other ASP.NET C# file.
The script is as follow:
Basically I wanted to send User Id and Account ID and then process the table:

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://rover.geodesic.net/wcv1/php/ProcessTrans.php?userid=" + item.Value + "&accountid=" + item.Key + "&type=stock");

// Set the 'Timeout' property in Milliseconds.
myRequest.Timeout = 600000;//10 mintutes
myRequest.Method = "GET";
HttpWebResponse newStream = (HttpWebResponse)myRequest.GetResponse();

if ((newStream.ContentLength > 0))
{
System.IO.StreamReader str = new System.IO.StreamReader(newStream.GetResponseStream());
Response.Write(str.ReadToEnd());
if (str != null) str.Close();
}

The small changes I did was, I multi threaded the process, as i was taking more time to execute the PHP page “ProcessTrans.php”;
In above example, Data has been sent in “GET”
If you want to Post Data to remote Web Page using HttpWebRequest :

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://rover.geodesic.net/wcv1/php/ProcessTrans.php?userid=" + item.Value + "&accountid=" + item.Key + "&type=stock");
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}

It might not work if the site you’re trying to stream is protected by authentication. If it’s Windows/NTLM Authentication and your account has privileges on the site, try using:
request.Credentials = CredentialCache.DefaultCredentials;
after the create request.

Ref: http://www.worldofasp.net/tut/WebRequest/Working_with_HttpWebRequest_and_HttpWebResponse_in_ASPNET_114.aspx

regards,

Categories: ASP.net C#, General, PHP