C# 和 PHP 做 溝通 [登錄、紀錄COOKIE、取資料]

C# 和 PHP 做 溝通 [登錄、紀錄COOKIE、取資料]

C# 和 PHP 做 溝通 [登錄、紀錄COOKIE、取資料]

 

PHP的部分

01. index.php

<?php

header(‘content-type:text/html;charset=utf-8’);

session_start();

 

//檢測是否登錄,若沒登錄則轉向登錄介面

if(!isset($_SESSION[‘username’])){

        header(“Location:login.html”);

        exit();

}

else{

       

        $arraydata=array();

        for($i=0;$i<5;$i++)

        {

                $arraydata[$i][“name”]=”jash”;

                $arraydata[$i][“password”]=”1234″;

        }

        echo json_encode($arraydata);     

}

?>

 

02. login.html

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

        <head>

        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />

        <title>登錄頁面</title>

          <style type=”text/css”>

                html{font-size:20px;}

                fieldset{width:300px; margin: 0 auto;}

                legend{font-weight:bold; font-size:24px;}

                .label{float:left; width:70px; margin-left:20px;}

                .left{margin-left:180px;font-size:18px;}

                .input{width:150px;}

                span{color: #666666;}

          </style>

        <script language=JavaScript>

        <!–

 

        function InputCheck(LoginForm)

        {

          if (LoginForm.username.value == “”)

          {

                alert(“請輸入帳號!”);

                LoginForm.username.focus();

                return (false);

          }

          if (LoginForm.password.value == “”)

          {

                alert(“請輸入密碼!”);

                LoginForm.password.focus();

                return (false);

          }

        }

 

        //–>

        </script>

        </head>

       

        <body>

                <div>

                        <fieldset>

                                <legend>登錄頁面</legend>

                                <form name=”LoginForm” method=”post” action=”login.php” onSubmit=”return InputCheck(this)”>

                                        <p>

                                        <label for=”username” class=”label”>帳  號:</label>

                                        <input id=”username” name=”username” type=”text” class=”input” />

                                        <p/>

                                        <p>

                                        <label for=”password” class=”label”>密  碼:</label>

                                        <input id=”password” name=”password” type=”password” class=”input” />

                                        <p/>

                                        <p>

                                        <input type=”submit” name=”submit” value=”  確  定  ” class=”left” />

                                        </p>

                                </form>

                        </fieldset>

                </div>

        </body>

</html>

 

03. login.php

<?php

header(‘content-type:text/html;charset=utf-8’);

session_start();

echo “<font size=’24’ face=’Arial’>”;//PHP放大字體

 

$username = htmlspecialchars($_POST[‘username’]);

$password = $_POST[‘password’];

 

if($username===’jash’ && $password==’1234′)

{

        //登錄成功

        $_SESSION[‘username’] = $username;

        exit(‘OK’);

} else {

        exit(‘fail’);

}

?>

 

 

C#部分

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

 

using System.Windows.Forms;

 

using System.Net;

using System.IO;

/*

//http://www.myhow2.net/wp/2012/09/c-visual-studio-2010%E4%B8%AD%E6%B2%A1%E4%BB%80%E4%B9%88%E6%89%BE%E4%B8%8D%E5%88%B0httputility-urlencode%E6%96%B9%E6%B3%95/

原因:Visual Studio 2010中建立的新專案,預設的編譯目標平臺是”.NET Framework 4.0 Client Profile”, 這個配置沒有包含System.Web assembly

 

解決方法:把編譯目標平臺改成“.NET Framework 4.0”,然後到Reference裡把System.Web Assembly 添加上。

 

Project -> Properties -> Application -> Target Framework

*/

using System.Web;

 

namespace CS2PHP

{

    public partial class Form1 : Form

    {

        //參考資料:http://www.cnblogs.com/Fooo/archive/2010/10/12/1848568.html

        public CookieContainer cc = new CookieContainer();

       

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            string url = “http://localhost:8080/cs2php/login.php”;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = “POST”;

            request.ContentType = “application/x-www-form-urlencoded”;

            request.CookieContainer=cc;

            string user = textBox1.Text; //用戶名

            string pass = textBox2.Text; //密碼

            string data = “username=” + HttpUtility.UrlEncode(user) + “&password=” + HttpUtility.UrlEncode(pass);

            request.ContentLength = data.Length;

            StreamWriter writer = new StreamWriter(request.GetRequestStream(),Encoding.ASCII);

            writer.Write(data);

            writer.Flush();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string encoding = response.ContentEncoding;

            if (encoding == null || encoding.Length < 1) {

                encoding = “UTF-8”; //預設編碼

            }

            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));

            data = reader.ReadToEnd();

            label1.Text = data;

            cc = request.CookieContainer;

            response.Close();

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            string url = “http://localhost:8080/cs2php/index.php”;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = “POST”;

            request.ContentType = “application/x-www-form-urlencoded”;

            request.CookieContainer = cc;

            string data;

            /*

            string user = textBox1.Text; //用戶名

            string pass = textBox2.Text; //密碼

            data = “username=” + user + “&password=” + pass;

            request.ContentLength = data.Length;

            StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);

            writer.Write(data);

            writer.Flush();

            */

 

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string encoding = response.ContentEncoding;

            if (encoding == null || encoding.Length < 1)

            {

                encoding = “UTF-8”; //預設編碼

            }

            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));

            data = reader.ReadToEnd();

            label1.Text = data;

            cc = request.CookieContainer;

            response.Close();

        }

    }

}

 

 

 

 

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *