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

本文关键字:最佳 方式 是什么 MySQL PHP | 更新日期: 2023-09-27 18:02:06

我正在构建一个需要登录的简单应用程序。目前,我正在从我的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#正确地操作PHP数据库和正确的安全性。

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

您可以通过实现一个简单的JSON API Server来实现c#与PHP的通信。

考虑以下内容: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下运行您的站点,因此您将通过以下URL访问api服务器:https://yoursite.com/api_server.php


下面是我在firefox上使用RESTClient插件在本地测试API服务器。

  • 成功场景:https://i.stack.imgur.com/PiEsW.png
  • 错误场景:https://i.stack.imgur.com/9tMx4.png

解决方案是:删除BOM:-)

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