Sending data to php from windows phone

2019-08-30 11:13发布

问题:

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.

回答1:

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;
    }
}


回答2:

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.