C# 製作存取 PHP類別[登錄(login.php)、傳送json資料(getjson.php) 、接收json資料(getjson.php)、接收json資料(getRAW.php)、額外使用wget post(wget_post.bat)]

C# 製作存取 PHP類別[登錄(login.php)、傳送json資料(getjson.php) 、接收json資料(getjson.php)、接收json資料(getRAW.php)、額外使用wget post(wget_post.bat)]

C# 製作存取 PHP類別[登錄(login.php)、傳送json資料(getjson.php) 、接收json資料(getjson.php)、接收json資料(getRAW.php)、額外使用wget post(wget_post.bat)]

 

CS_PHP.CS

   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*
//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;
using System.Net;
using System.IO;//CookieContainer

namespace OOOO_XXXX
{
    public class CS_PHP
    {
        public String m_StrDomain;
        private CookieContainer m_CookieContainer;
        public CS_PHP()
        {
            m_StrDomain = “http://localhost:8080/cs2php/”;
            m_CookieContainer = new CookieContainer();
        }
        public String loginPHP(String PHPName, String StrUserName, String StrPassword)
        {
            string url = m_StrDomain + PHPName;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = “POST”;
            request.ContentType = “application/x-www-form-urlencoded”;
            request.CookieContainer = m_CookieContainer;
            string user = StrUserName; //用户名
            string pass = StrPassword; //密码
            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();

            m_CookieContainer = request.CookieContainer;
            response.Close();

            return data;
        }

        public String runPHP(String PHPName)
        {
            string url = m_StrDomain + PHPName;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = “POST”;
            request.ContentType = “application/x-www-form-urlencoded”;
            request.CookieContainer = m_CookieContainer;
            string data;

            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();
            
            m_CookieContainer = request.CookieContainer;
            response.Close();

            return data;
        }
        public String runPHP(String PHPName, String StrData,bool blnRAW=false)
        {
            string url = m_StrDomain + PHPName;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = “POST”;
            request.ContentType = “application/x-www-form-urlencoded”;
            request.CookieContainer = m_CookieContainer;

            string data=””;
            if (!blnRAW)
            {
                data = “data=” + HttpUtility.UrlEncode(StrData);
            }
            else
            {
                data = HttpUtility.UrlEncode(StrData);
            }
            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();

            m_CookieContainer = request.CookieContainer;
            response.Close();

            return data;
        }

    }
}

 

wget_post.bat

wget –post-data=”data=123456789″ http://localhost:8080/cs2php/getjson.php -O log_01.txt

wget –post-data=”987654321″ http://localhost:8080/cs2php/getRAW.php -O log_02.txt

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’);

}

?>

getRAW.php

<?php
/*
資料來源:http://phpwolf.blogspot.tw/2013/08/php-post-json.html
讓 PHP 接收 post 的 json 資料
我們在串接API的時候會用到 CURL 函式 POST 資料給 JSON 接收,雖然我們是使用 POST 傳出資料。但是我們在接收的 SERVER 端使用 $_POST 卻抓不到任何資料。

原來 PHP 默認只支援 application/x-www.form-urlencoded 來把資料塞入到  $_POST  所以即便你用 POST 傳值過來,也不能用 $_POST 來取值。

這時候我們就要用 $GLOBALS[‘HTTP_RAW_POST_DATA’] 來取得資料了。因為其實SERVER端是有拿到資料的,所以用這個參數就可以拿到”完整”資料。

後記:
後來又出現了一個問題,$GLOBALS[‘HTTP_RAW_POST_DATA’] 如果要可以正確取得資料,需要去把 php.ini 中的功能打開,這對很多專案中客戶是採用虛擬主機的是一個很大的問題。好險有另一個方式也可以取得原始的 post 資料:
*/
header(‘content-type:text/html;charset=utf-8’);

$data = file_get_contents(“php://input”);
echo urldecode($data).”_get”;
?>

getjson.php

<?php

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

 

 

$data = $_POST[‘data’];

$obj= json_decode($data);

 

print_r($obj);

 

foreach($obj as $key => $value) {

    if($value) {

 

            //how to use json array to insert data in Database

        echo “$value->name”.” $value->password”.”\n”;

    }

}

 

echo $data.’_get’;

?>

outjson.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);     

}

?>

 

 

 

發表迴響

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