我正在构建一个需要登录的简单应用程序。然而,目前我正从我的C#应用程序直接连接到我的数据库,但是,由于某种原因,使用它的大学网络不允许直接连接到MySQL。我决定看看如何用PHP来代替它。我已经构建了一个简单的登录表单,并对其进行了测试,它似乎是有效的。然而,我有一些问题和问题需要解决。
首先,我将如何停止任何人输入PHP文件的地址并将数据取回?
第二,如何才能获得多个结果?假设我创建了一个获取所有用户文件并将其存储在C#应用程序中的PHP文件,我如何从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正确地操作数据库。
发布于 2014-05-07 15:17:20
您可以通过实现一个简单的JSON与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#与其进行通信,发出帖子请求:
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:server.php访问api服务器
下面是我在火狐上使用RESTClient插件在本地测试API服务器。
发布于 2019-09-09 19:21:03
解决方案是:删除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;
}
}https://stackoverflow.com/questions/23521175
复制相似问题