1. 程式人生 > >PHP中curl的CURLOPT_POSTFIELDS請求時,Content-Type多出boundary=------------------------

PHP中curl的CURLOPT_POSTFIELDS請求時,Content-Type多出boundary=------------------------

當我們採用 CURL 在不注意細節的前提下向伺服器傳送一些資料,得到請求頭的CONTENT_TYPE:

[CONTENT_TYPE] => multipart/form-data; boundary=—————————-f924413ea122



後面多出一個boundary,導致服務端獲取不到提交的引數。

解決辦法:

curl_setopt ( $curl, CURLOPT_POST, 1);
curl_setopt ( $curl, CURLOPT_HTTPHEADER,array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt ( $curl, CURLOPT_POSTFIELDS,http_build_query($params));

http_build_query($post_data) 來替代 $post_data 再向這個 PHP 指令碼提交資料的時候,我們就會得到和上面不同的結果,這才是我們理想中的結果:



原因分析:

從上面這個例子中不難看出,使用 CURL 並且引數為資料時,向伺服器提交資料的時候,HTTP頭會發送Content_type: application/x-www-form-urlencoded。這個是正常的網頁<form>提交表單時,瀏覽器傳送的頭部。而 multipart/form-data 我們知道這是用於上傳檔案的表單。包括了 boundary 分界符,會多出很多位元組。
官方的手冊上是這樣說的:

The full data to post in a HTTP “POST” operation. To post a file, prepend a filename with @ and use the full path. This can either be passed as a urlencoded string like ‘para1=val1¶2=val2&…' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

使用陣列提供 post 資料時,CURL 元件大概是為了相容 @filename 這種上傳檔案的寫法,預設把 content_type 設為了 multipart/form-data。雖然對於大多數伺服器並沒有影響,但是還是有少部分伺服器不相容。

經過一番總結最終得出結論:在沒有需要上傳檔案的情況下,儘量對 post 提交的資料進行 http_build_query 處理,然後再發送出去,能實現更好的相容性,更小的請求資料包。