在C#中使用PHP和MySQL的最佳方法是什么?

时间:2014-05-07 14:51:16

标签: c# php mysql

我正在构建一个需要登录的简单应用程序。目前我正在从我的C#应用​​程序直接连接到我的数据库,然而,将使用它的学院网络由于某种原因不允许直接连接到MySQL。我决定看看我将如何从PHP中做到这一点。我已经构建了一个简单的登录表单并对其进行了测试,它似乎可行。但是我有一些问题需要整理出来。

我首先会如何阻止任何人输入PHP文件的地址并获取数据?

其次,我将如何获得多个结果?假设我创建一个PHP文件来获取所有用户的文件并将它们存储在C#应用程序中,我如何从PHP文件中实际解析它?

以下是我在服务器上拥有的login.php文件示例:

    <?php

include("connect.php");

$username = mysql_escape_string($_GET['username']);
$password = mysql_escape_string($_GET['password']);

$squery = mysql_query("SELECT * FROM users WHERE username='$username'");
$query = mysql_fetch_array($squery);
$rowcount = mysql_num_rows($squery);

if($rowcount == 1)
{
    if($password != $query['password'])
        echo'Password errata';
    else
        echo 'Login avvenuto';
}
else
    echo 'Account non registrato';

?>

以下是我在C#上用来访问PHP文件的代码:

string Reply = new WebClient().DownloadString("http://127.0.0.1/ClipCloud.Service/account_auth/login.php?username=" + textBox1.Text + "&password=" + textBox2.Text);
            switch (Reply.ToLower())
            {
                case "account non registrato":
                    {
                        MessageBox.Show("Account not registered!");
                        break;
                    }
                case "password errata":
                    {
                        MessageBox.Show("Password error!");
                        break;
                    }
                case "login avvenuto":
                    {
                        MessageBox.Show("Login happened!");
                        break;
                    }
                default:
                    {
                        MessageBox.Show("Error with the remote server, please let try again later!");
                        break;
                    }
            }

很抱歉,如果这个问题有点令人困惑,我基本上只需要知道如何使用C#正确操作数据库,并使用正确的安全性。

2 个答案:

答案 0 :(得分:8)

通过实现简单的JSON API服务器,您可以使用C#进行通信。

请注意以下事项: http://yoursite.com/api_server.php

<强> api_server.php

<?php

// Load Request
$api_method = isset($_POST['api_method']) ? $_POST['api_method'] : '';
$api_data = isset($_POST['api_data']) ? $_POST['api_data'] : '';

// Validate Request
if (empty($api_method) || empty($api_data)) {
    API_Response(true, 'Invalid Request');
}
if (!function_exists($api_method)) {
    API_Response(true, 'API Method Not Implemented');
}

// Call API Method
call_user_func($api_method, $api_data);

/* Helper Function */

function API_Response($isError, $errorMessage, $responseData = '')
{
    exit(json_encode(array(
        'IsError' => $isError,
        'ErrorMessage' => $errorMessage,
        'ResponseData' => $responseData
    )));
}

/* API Methods */

function loginUser($api_data)
{
    // Decode Login Data
    $login_data = json_decode($api_data);

    // Dummy Check
    if ($login_data->username == 'test' &&
        $login_data->password == '1234')
    {
        // Success
        API_Response(false, '', 'SUCCESS');
    }
    else
    {
        // Error
        API_Response(true, 'Invalid username and/or password.');
    }
}

?>

然后你通过C#与它进行通信,发出POST请求:

using (var wb = new WebClient())
{
    var data = new NameValueCollection();
    data["api_method"] = "loginUser";
    data["api_data"] = "{ \"username\":\"test\", \"password\":\"1234\" }";

    var responseBytes = wb.UploadValues(
        "http://yoursite.com/api_server.php", "POST", data);

    string responseString = Encoding.Default.GetString(responseBytes);
}

此处,API服务器中的responseString将为json字符串。要对此进行解码,您可以使用:http://james.newtonking.com/json


以下是一个完整的示例,说明如何使用简单的控制台应用程序将所有内容整合到C#应用程序中:

注意我是如何通过json库生成json字符串(对于api_data),而不是手动输入它。

using System;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using Newtonsoft.Json;

namespace TemplateFive
{
    public class API_Response
    {
        public bool IsError { get; set; }
        public string ErrorMessage { get; set; }
        public string ResponseData { get; set; }
    }

    public class Login_Request
    {
        public string username { get; set; }
        public string password { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // request params
            string apiUrl = "https://yoursite.com/api_server.php";
            string apiMethod = "loginUser";
            Login_Request myLogin_Request = new Login_Request()
            {
                username = "test",
                password = "1234"
            };

            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod                                    },
                { "api_data",   JsonConvert.SerializeObject(myLogin_Request) }
            });

            // decode json string to dto object
            API_Response r = 
                JsonConvert.DeserializeObject<API_Response>(response);

            // check response
            if (!r.IsError && r.ResponseData == "SUCCESS")
            {
                Console.WriteLine("login success");
            }
            else
            {
                Console.WriteLine("login error, reason is: {0}",
                    r.ErrorMessage);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    }

    public static class Http
    {
        public static String Post(string uri, NameValueCollection pairs)
        {
            byte[] response = null;
            using (WebClient client = new WebClient())
            {
                response = client.UploadValues(uri, pairs);
            }
            return Encoding.Default.GetString(response);
        }
    }
}

最后,要保护整个网站,请使用SSL运行您的网站,以便通过以下网址访问api服务器:https://yoursite.com/api_server.php


我在这里使用firefox上的RESTClient插件在本地测试API服务器。

答案 1 :(得分:0)

解决方法是:删除物料清单:-)

   static class Http
{
    public static String Post(string uri, NameValueCollection pairs)
    {
        byte[] response = null;
        using (WebClient client = new WebClient())
        {
            response = client.UploadValues(uri, pairs);
        }
        string ret = Encoding.UTF8.GetString(response);
        ret = ret.Trim(new char[] { '\uFEFF', '\u200B' });//removes the BOM 
        return ret;
    }
}