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; /* 解决方法:把编译目标平台改成“.NET Framework 4.0”,然后到Reference里把System.Web Assembly 添加上。 Project -> Properties -> Application -> Target Framework namespace OOOO_XXXX StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); m_CookieContainer = request.CookieContainer; return data; public String runPHP(String PHPName) HttpWebResponse response = (HttpWebResponse)request.GetResponse(); return data; string data=””; StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); m_CookieContainer = request.CookieContainer; 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 原來 PHP 默認只支援 application/x-www.form-urlencoded 來把資料塞入到 $_POST 所以即便你用 POST 傳值過來,也不能用 $_POST 來取值。 這時候我們就要用 $GLOBALS[‘HTTP_RAW_POST_DATA’] 來取得資料了。因為其實SERVER端是有拿到資料的,所以用這個參數就可以拿到”完整”資料。
後記: $data = file_get_contents(“php://input”); |
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); } ?> |