C# PHP communication - c#

I'm writing an app that will authenticate user from a MySQL database.
I have written it in Java (android) but am now porting to Windows phone.
the PHP file uses $get and then echoes the response:
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$query_search = "select * from users where user = '".$username."'";
//$query_search = "select * from users where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
} else {
echo "User Found";
}
How can I pass the username variable to PHP and then receive the result?

YOUR CODE IS VULNERABLE TO SQL-INJECTION METHOD USE PDO/MYSQLi to AVOID THIS
Create loaded event handler:
using System;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
System.Uri myUri = new System.Uri("Your php page url");
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),myRequest);
}
creating "POST" data stream:
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);
// Create the post data
string postData = "username=value";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}
receive response:
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
Debug.WriteLine(result);
}
}

use a in-linky stuff like I have a script in my server and you just write: "example.com/save.php?username=textbox1.text&score=points"

Related

Getting a reponse from a web api in JSON format

I am new with web service and API's and trying to get a response from a URL with a post method and passing a parameter to it. I am developing a C# winform application that sending request to this api and must return the output in JSON format. Below is my code so war i only getting an OK response instead of the actual JSON data.
private void button1_Click(object sender, EventArgs e)
{
string postData = "station=sub";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Uri target = new Uri("http://apijsondata/tz_api/");
WebRequest myReq = WebRequest.Create(target);
myReq.Method = "POST";
myReq.ContentType = "application/x-www-form-urlencoded";
myReq.ContentLength = byteArray.Length;
using (var dataStream = myReq.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (var response = (HttpWebResponse)myReq.GetResponse())
{
//Do what you need to do with the response.
MessageBox.Show(response.ToString());
}
}
You should use a StreamReader together with HttpWebResponse.GetResponseStream()
For example,
var reader = new StreamReader(response.GetResponseStream());
var json = reader.ReadToEnd();

Passing C# Web service Parameters to PHP Application

I am trying to passing C# Web service Parameters to PHP Application but not getting below is my code. Actually I am passing username and password xml format because no buddy should not see that credential while passing.
Below is my C# Web service using asp.net web form button click to redirect PHP application.
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
StringBuilder strRequest = new StringBuilder();
string url = "http://xyz.in/getuser.php/";
req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(username,password);
writer.Close();
rsp = req.GetResponse();
var sr = new StreamReader(rsp.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
}
Below is my button click code.
protected void Button2_Click(object sender, EventArgs e)
{
localhost.WebService objserv1 = new localhost.WebService();
Label.Text = objserv1.POSTXml("nagapavani", "tech#1234");
}
Actually when user will button click passing some values to web service and through web service want to pass that value to php application. Is there Other way to achieve that requirement. When I am going to button click not going to redirect and taken this code from google.
You could send the data as following. Convert it to a byte array and write it to the request stream:
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
string data = "user=" + username + "&password=" + password;
string url = "http://xyz.in/getuser.php/";
byte[] buffer = Encoding.ASCII.GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
using (Stream PostData = WebReq.GetRequestStream())
{
PostData.Write(buffer, 0, buffer.Length);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using (Stream stream = WebResp.GetResponseStream())
{
using (StreamReader strReader = new StreamReader(stream))
{
return strReader.ReadToEnd();
}
}
WebResp.Close();
}
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
return String.Empty;
}

Sending data to php from windows phone

I need to send some data from windows phone 7 to php page through POST method, I have the following code at wp7 side
public void SendPost()
{
var url = "http://localhost/HelpFello/profile.php";
// Create the web request object
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Start the request
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
MessageBox.Show("data sent");
}
void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);
// Create the post data
// Demo POST data
string postData = "user_id=3&name=danish&email_id=mdsiddiquiufo&password=12345&phone_Number=0213&about_me=IRuel2&rating=5";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
var Response = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
}
catch (WebException e)
{
MessageBox.Show(e.ToString());
}
}
and following on my localhost, to send the data to database
<?php
require_once("constants.php");
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$email_id = $_POST['email_id'];
$password = $_POST['password'];
$phone_number = $_POST['phone_number'];
$about_me = $_POST['about_me'];
$rating = $_POST['rating'];
$query="INSERT INTO profile(User_ID,Name,Email_ID,password,Phone_Number,About_Me,Rating) VALUES ({$user_id},'{$name}','{$email_id}','{$password}',{$phone_number}, '{$about_me}' , {$rating})";
mysql_query($query,$connection);
mysql_close($connection);
?>
When I run the code I have no errors it means code is working fine, but no data is inserted in the database.
I think there is a better way than HttpWebRequest. That is WebClient. You can change the method there and append data like you do in get string. key=value&key2=value then when you invoke that request and get the response try debugging and getting the output from VS or if that is difficult simply assign he string to a textblock in the code. You will get to know if that page has been ever executed or not.
A sample code :
WebClient wc = new WebClient();
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
Parameters prms = new Parameters();
prms.AddPair("email", email);
prms.AddPair("password", password);
wc.UploadStringAsync(new Uri(loginUrl), "POST", prms.FormPostData(), null);
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
// e.Result will contain the page's output
}
// This is my Parameters and Parameter Object classes
public class Parameters
{
public List<ParameterObject> prms;
public Parameters()
{
prms = new List<ParameterObject>();
}
public void AddPair(string id, string val)
{
prms.Add(new ParameterObject(id, val));
}
public String FormPostData()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < prms.Count; i++)
{
if (i == 0)
{
buffer.Append(System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
else
{
buffer.Append("&" + System.Net.HttpUtility.UrlEncode(prms[i].id) + "=" + System.Net.HttpUtility.UrlEncode(prms[i].value));
}
}
return buffer.ToString();
}
}
public class ParameterObject
{
public string id;
public string value;
public ParameterObject(string id, string val)
{
this.id = id;
this.value = val;
}
}
First error: assuming that no error messages means success
Second error: gaping SQL injection holes
first fix: always assume queries will fail, and check for that condition:
$result = mysql_query($query) or die(mysql_error());
second fix: ditch the mysql_() functions and switch to PDO using prepared statements with placeholders. Boom. No more injection problems, and your code won't stop working on you when mysql_() is removed in a future PHP version.
ps..
3rd error: no quotes on your phone number value. So someone submits 867-5309, and you end up inserting -4442 because mysql saw it as two numbers being subtracted, not a string.

Set request properties in Asynchronous web request failed. C#

private void LoginButton_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
IAsyncResult result = request.BeginGetResponse(
new AsyncCallback(DeleResponse), request);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here is the method which called to on button click event
private void DeleResponse(IAsyncResult result)
{
byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
LoginButton.Text = "Logging in...";
LoginButton.Enabled = false;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
request.Method = "Post";
request.CookieContainer = authCookie;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
postWriter = request.GetRequestStream();
postWriter.Write(PostData, 0, PostData.Length);
postWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
if (loginValidateString.Contains(LoggedKeyword))
{
some process here:
}
else if( FAILKEYWORDCHECK HERE)
{
login page process here;
}
}
The problem is when I check this with fiddler I can see only following header properties.
Connection: Keep-Alive;
Host: www.example.com
What would be the reason that I can't set properties in the request header?
Edit: Added synchronous request method which I already achieved without any errors.
private void LoginButton_Click(object sender, EventArgs e)
{
try
{
LoginButton.Text = "Logging in...";
LoginButton.Enabled = false;
byte[] PostData = Encoding.UTF8.GetBytes("username=" + userInp.Text + "&password=" + passInp.Text + extraLoginPostString);
request = (HttpWebRequest)WebRequest.Create(loginUrl);
request.Method = "Post";
request.CookieContainer = authCookie;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
postWriter = request.GetRequestStream();
postWriter.Write(PostData, 0, PostData.Length);
postWriter.Close();
response = (HttpWebResponse)request.GetResponse();
string serverData = new StreamReader(response.GetResponseStream()).ReadToEnd();
string loginValidateString = response.GetResponseHeader(loginValidateStringHolder);
if (loginValidateString.Contains(LoggedKeyword))
{
MessageBox.Show("Logged in Successfully");
foreach (Cookie cookieReader in response.Cookies)
{
authCookie.Add(cookieReader);
}
Success method continues..
}
else if (loginValidateString.Contains(failedLogKeyword))
{
Failed process
}
}
catch
{
Catchblock
}
}
Means, I just know how to set properties for normal requests.
You're trying to set properties of the request when the response is available. You need to set the request properties before you make the request to the server - so you should be setting them in LoginButton_Click, not in the response handling code. Likewise you can't use GetRequestStream in a callback for BeginGetResponse. Roughly speaking, you want:
In the initial event handler:
Create the request
Set simple properties
Call BeginGetRequestStream
In the callback handler for BeginGetRequestStream
Write out the body data
Call BeginGetResponse
In the callback handler for BeginGetResponse
Handle the response data
Alternatively, unless you have to use the asynchronous calls, you could just create a separate thread and use the synchronous versions instead. Until the language support in C# 5, that would be simpler.

Can't Login to cPanel with C# WebRequest

I am struggling to develop a C# class to login to cPanel on a web host (Hostgator).
In PHP it is quite easy using the Curl extension as follows:
$url = "http://mysite.com:2082/";
$c = curl_init($url);
curl_setopt($c, CURLOPT_USERPWD, 'user:password');
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($c);
if ($result === false)
$result = curl_error($c);
curl_close($c);
file_put_contents('log.txt', $result);
//print_r($result);
Now here is my C# class with the various attempts to make it work commented out:
class HTTPHandler
{
public static string Connect (string url, string userName, string password)
{
string result;
try
{
// An initial # symbol in the password must be escaped
if (password.Length > 0)
if (password[0] == '#')
password = "\\" + password;
// Create a request for the URL.
WebRequest request = WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(userName, password);
/*
var credCache = new CredentialCache();
credCache.Add(new Uri(url), "Basic",
new NetworkCredential(userName, password));
request.Credentials = credCache;
*/
//request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";
/*
// Create POST data and convert it to a byte array.
string postData = string.Format("user={0}&pass={1}", userName, password);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
*/
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Display the content.
result = string.Format("Server response:\n{0}\n{1}", response.StatusDescription, reader.ReadToEnd());
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception e)
{
result = string.Format("There was an error:\n{0}", e.Message);
}
return result;
}
}
}
But I keep getting an error 401 (Unauthorized) at the GetResponse stage.
When I compare the $_SERVER vars in my local host test page between the PHP and C# submissions, I get the same data apart from the sender port being a bit different. The crucial PHP_AUTH_USER and PHP_AUTH_PW are the same.
My OS is Windows 7 64 bit and I am using Visual C# 2010.
I guess the solution is really simple, but so far I am baffled. But a relative newbie to C#. I hope somebody can help.
You don't really need to set PreAuthenticate, just let the request figure it out. Also I would suggest using HttpWebRequest instead of WebRequest. The main difference is that you can set CookieContainer property to enable cookies. This is a bit confusing since by default it will have cookies disabled and all you need to do is to set it to new CookieContainer(); to enable cookies for your request.
This matters because of the redirects that happen during authentication and the auth cookie that records the fact that you successfully authenticated.
Also a coding style note: please make sure to wrap all the IDisposables (such as response, stream and reader) in the using() statement.
Also I am unclear why are you escaping # in the password. Request should take care of all your encoding needs automagically.
Complete sample code:
var request = WebRequest.CreateHttp(url);
request.Credentials = new NetworkCredential(username, password);
request.CookieContainer = new CookieContainer(); // needed to enable cookies
using (var response = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)))
return string.Format("Server response:\n{0}\n{1}", response.StatusDescription, reader.ReadToEnd());
edit: Sorry for all the edits. I was writing code by memory and was struggling a bit with getting the encoding part right.
This is using System.Web where I had to set the project properties to use the full .NET Framework 4 to gain access to this assembly for the HttpUtility and add a reference to System.Web in References.
I didn't test all the overloaded methods but the main thing is the cPanel connection where the authentication credentials are added to the http header when a userName is present.
Also, for cPanel I needed to set request.AllowAutoRedirect = false; so that I control page by page access since I didn't manage to capture cookies.
Here is the code for the HTTP Helper Class that I came up with:
class HTTPHandler
{
// Some default settings
const string UserAgent = "Bot"; // Change this to something more meaningful
const int TimeOut = 1000; // Time out in ms
// Basic connection
public static string Connect(string url)
{
return Connect(url, "", "", UserAgent, "", TimeOut);
}
// Connect with post data passed as a key : value pair dictionary
public static string Connect(string url, Dictionary<string, string> args)
{
return Connect(url, "", "", UserAgent, ToQueryString(args), TimeOut);
}
// Connect with a custom user agent specified
public static string Connect(string url, string userAgent)
{
return Connect(url, "", "", userAgent, "", TimeOut);
}
public static string Connect(string url, string userName, string password, string userAgent, string postData, int timeOut)
{
string result;
try
{
// Create a request for the URL.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (userAgent == null)
userAgent = UserAgent;
request.UserAgent = userAgent;
request.Timeout = timeOut;
if (userName.Length > 0)
{
string authInfo = userName + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
request.AllowAutoRedirect = false;
}
if (postData.Length > 0)
{
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create POST data and convert it to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
}
// Get the response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
using (StreamReader reader = new StreamReader(dataStream))
{
result = string.Format("Server response:\n{0}\n{1}", response.StatusDescription, reader.ReadToEnd());
}
}
}
catch (Exception e)
{
result = string.Format("There was an error:\n{0}", e.Message);
}
return result;
}
public static string ToQueryString(Dictionary<string, string> args)
{
List<string> encodedData = new List<string>();
foreach (KeyValuePair<string, string> pair in args)
{
encodedData.Add(HttpUtility.UrlEncode(pair.Key) + "=" + HttpUtility.UrlEncode(pair.Value));
}
return String.Join("&", encodedData.ToArray());
}
}

Categories