2013-03-06 40 views
1

我有下面的頁面。JSON over cURL在PHP不工作

json.php

$json_data = array(
    'first_name' => 'John', 
    'last_name' => 'Doe', 
    'birthdate' => '12/02/1977', 
    'files'  => array(
     array(
      'name' => 'file1.zip', 
      'status' => 'good' 
     ), 
     array(
      'name' => 'file2.zip', 
      'status' => 'good' 
     ) 
    ) 
); 

$url = 'http://localhost/test.php'; 

$content = json_encode($json_data); 

$curl = curl_init(); 

curl_setopt($curl, CURLOPT_URL, $url); 
curl_setopt($curl, CURLOPT_HEADER, false); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_HTTPHEADER, 
    array(
     "Content-type: application/json", 
     "Content-Length: " . strlen($content) 
    ) 
); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, 'json=' . urlencode($content)); 
curl_setopt($curl, CURLINFO_HEADER_OUT, true); 

$json_response = curl_exec($curl); 

$status  = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
$header_sent = curl_getinfo($curl, CURLINFO_HEADER_OUT); 

curl_close($curl); 

echo $header_sent; 
echo '<br>'; 
echo $status; 
echo '<br>'; 
echo $json_response; 

test.php

echo '<pre>'; 
print_r($_POST); 
echo '</pre>'; 

當我從瀏覽器調用json.php,我得到以下結果:

POST /json.php HTTP/1.1 Host: localhost Accept: */* Content-type: application/json Content-Length: 150 
200 

Array 
(
) 

爲什麼我無法看到我想要發送的POST字符串?

編輯:

如果我不設置Content-type: application/json頭(按@ landons的評論),我得到以下結果:

POST /ddabvd/widendcm/widendcm-finished.php HTTP/1.1 Host: localhost Accept: */* Content-Length: 150 Content-Type: application/x-www-form-urlencoded 
200 
Array 
(
    [json] => {"first_name":"John","last_name":"Doe","birthdate":"12\/02\/1977","files":[{"name": 
) 
+1

當您不發送應用程序/ json內容類型標頭時會發生什麼? – landons 2013-03-06 20:35:30

+0

@landons我得到字符串截斷。 (請參閱我的更新。) – Alex 2013-03-06 20:41:21

+2

不要對非多部分和非urlencoded內容使用'$ _POST'數組。使用'var_dump(file_get_contents('php:// input'));' – Wrikken 2013-03-06 20:50:12

回答

2

PHP不使用它的內部請求解析對於POST請求,如果內容類型未設置爲在瀏覽器內發佈表單時使用的兩種官方內容類型之一。 (例如,唯一允許的內容類型是multipart/form-data,通常用於文件上傳,默認值爲application/x-www-form-urlencoded)。

如果你想使用不同的內容類型,你是你自己的,例如,您在從php://input獲取請求主體時必須自己完成所有解析。

實際上,您的內容類型目前是錯誤的。它不是application/json,因爲數據讀取json={...},這在被解析爲json時是不正確的。

+0

爲了補充一點,您可能會將內容作爲郵件正文發送,而不是作爲cURL中的郵件字段。這在通過JSON的RESTful服務中更爲常見。 – 2013-03-06 21:53:12