本文轉自:https://blog.csdn.net/pangchengyong0724/article/details/52103962
本地模擬請求服務器數據,請求數據格式為json,服務器返回數據也是json. 由於需求特殊性, 如同步客戶端的批量數據至雲端, 提交至服務器的數據可能是多維數組數據了. 這時需要將此數據以一定的數據編碼方式(json格式)來組織並提交.以便服務器很好地處理.
客戶端curl模擬提交代碼.
function http($url, $data = NULL, $json = false) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); if (!empty($data)) { if($json && is_array($data)){ $data = json_encode( $data ); } curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); if($json){ //發送JSON數據 curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json; charset=utf-8', 'Content-Length:' . strlen($data)) ); } } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($curl); $errorno = curl_errno($curl); if ($errorno) { return array('errorno' => false, 'errmsg' => $errorno); } curl_close($curl); return json_decode($res, true); }
參數說明:
url:服務器接收處理urlurl:服務器接收處理urldata: 數組形式的post數據
$json: 是否以json方式提交(1: 是, 0:否)
服務器端獲取post數據代碼:
print_r($_POST);
最后獲取到的數據是空值.
上網搜索了一下發現PHP默認只識別application/x-www.form-urlencoded標准的數據類型,修改頭信息也沒有結果…只能通過以下方式獲得數據
//第一種方法 $post = $GLOBALS[‘HTTP_RAW_POST_DATA’]; //第二種方法 $post = file_get_contents(“php://input”);
最后修改后,數據才能接收到
