.NET POST到PHP页面页面、NET、POST、PHP

2023-09-04 06:21:29 作者:殇

我想从我的发送本机的IP地址authenticate.php我的Web服务器上的C#.NET应用程序实现一个非常基本的系统。 PHP页面将检查该IP地址对数据库,要么用回响应是或否。

I am trying to implement a very basic system from my C# .NET application that sends the IP address of the machine to authenticate.php on my web server. The php page will check this IP address against a database and either respond back with "yes" or "no".

这一直以来,我曾与PHP的很长一段时间,我有点糊涂了。这里是我的.NET函数的模样。

It has been a long time since I worked with PHP, and I am a little bit confused. Here is what my .NET function looks like.

public static bool IsAuthenticated()
{
    string sData = getPublicIP();
    Uri uri = new Uri("http://www.mysite.com/authenticate.php");
    if (uri.Scheme == Uri.UriSchemeHttp)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = WebRequestMethods.Http.Post;
        request.ContentLength = sData.Length;
        request.ContentType = "application/x-www-form-urlencoded";

        // POST the data to the authentication page
        StreamWriter writer = new StreamWriter(request.GetRequestStream());
        writer.Write(sData);
        writer.Close();

        // Retrieve response from authentication page
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string sResponse = reader.ReadToEnd();
        response.Close();

        if (sResponse == "yes")
        {
            Console.WriteLine("Authentication was Successful.");
            return true;
        }
        else
        {
            Console.WriteLine("Authentication Failed!");
            return false;
        }
    }
}

所以会在POST变量$ _ POST ['SDATA'];而我怎么回应回我,结果应用程序?

So would the POST variable be $_POST['sData']; and how do I respond back to my application with the result?

推荐答案

假设值 SDATA 就是(说)10.1.1.1那么你现在不张贴在第一时间正确的表格数据。变量的名称是不写的

Assuming the value of sData is (say) "10.1.1.1" then you're currently not posting proper form data in the first place. The name of the variable isn't part of the text written by

 writer.Write(sData);

您需要做的是这样的:

 string postData = "ipaddress=" + sData;

,然后用你的PHP中的 ip地址表单参数。

还请注意,你应该给予的二进制的内容长度,这可能不是相同的串的长度在字符。当然,这没关系,如果这里的字符串完全是ASCII码,这是我所期待,如果它是一个IP地址,...但它是值得铭记用于其他用途。 (同样,你通常需要牢记这需要特殊编码的字符。)

Note also that you should be giving the binary content length, which may not be the same as the string length in characters. Of course it's okay if the string here is entirely ASCII, which I'd expect if it's an IP address... but it's worth bearing in mind for other uses. (Likewise you would normally need to bear in mind any characters which need special encoding.)

另外请注意,这将是更好地使用使用语句的的StreamWriter HTT presponse 等,以确保即使抛出一个异常,一切都被关闭。

Also note that it would be better to use using statements for the StreamWriter, HttpResponse etc, to make sure that everything gets closed even if an exception is thrown.