2020年6月2日 星期二

PHP 接收 post 的 json 資料

讓 PHP 接收 post 的 json 資料
- 8月 02, 2013
我們在串接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 資料:


echo $data = file_get_contents("php://input");




---------------------------------------------------------------------------------------------


<?php
    header ('Content-Type: text/html; charset=UTF8');

        $name = $_POST["name"];
        $order_date= $_POST["order_date"];
        $price = $_POST["price"];
   
    //建立資料連線
    $link=mysql_connect("sql102.000space.com","space_13936932","nate8586");

    if(!$link){
                echo("Failure");
    }

    //開啟資料庫
    $db_selected=mysql_select_db("space_13936932_breakfast",$link);

    if(!$db_selected){
                echo("not open space_13901458_breakfast<br>".mysql_error($link));
    }

        mysql_query("SET NAME 'UTF8'");
        mysql_query('SET NAMES utf8');
        mysql_query('SET CHARACTER_SET_CLIENT=utf8');
        mysql_query('SET CHARACTER_SET_RESULTS=utf8');


        //新增資料
        $sql="insert into breakfast(order_date, name, price, status) VALUES ('$order_date', '$name', '$price', '0')";

        if (mysql_query($sql,$link)){
                echo "Database my_db created";
        }else{
                echo "Error creating database: " . mysql_error();
        }

    //釋放查詢結果所佔用的記憶體
    mysql_free_result($result);

    //關閉資料庫
    mysql_close($link);
?>


--------------------------------------------------------------------------------------


<?php if($_SERVER['REQUEST_METHOD'] == "POST"){ $inputJson = $_POST['inputJson']; if(!empty($inputJson)){ //...... }else{ $json = array("status" => 1, "msg" => "inputJson is empty"); } }else{ $json = array("status" => 1, "msg" => "Request method not accepted"); } header('Content-type: application/json;charset=utf-8'); echo json_encode($json); ?>



-------------------------------
註:以下是我測試成功的案例:

send.php
<?php
/*
* post 傳送JSON 格式資料
* @param $url string URL
* @param $data_string string 請求的具體內容
* @return array
*   code 狀態碼
*   result 返回結果
*/
function post_json_data($url, $data_string) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return array('code'=>$return_code, 'result'=>$return_content);
}
$arr = array('a'=>'555','b'=>56454564);
var_dump(post_json_data('https://www.apiserver.com/receive.php', json_encode($arr)));

?>


https://www.apiserver.com/receive.php
<?php

$data = json_decode(file_get_contents('php://input'), true);
 

$dbhost = 'localhost';
$dbuser = 'xxxx';
$dbpass = 'xxxxxxx';
$dbname = 'xxxxxxx';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
//mysqli 預設編號為latin-1,建立資料庫已指定utf8編碼,所以要指定連線時所用編碼
$mysqli->query("SET NAMES utf8");

$sql = "INSERT INTO 66shop_request_log(header_text) VALUES (?)";

$stmt = $mysqli->prepare($sql);
//$stmt->bind_param('s',var_dump(json_encode($data)));
$stmt->bind_param('s',$data['a']);
$stmt->execute();

$stmt->close();
$mysqli->close();

echo "hello world!";


?>




沒有留言:

張貼留言

如何判斷現在FORM是在 insert mode? 還是 update mode?

只要用  if (empty({primary_key})) 就可以知道是否為新增模式了。 如果 {promary_key} 是空白的,那麼就是在新增模式;反之,就是更新模式。 以上。