php curl POST 編碼方式 multipart/form-data與application/x-www-form-urlencode的區別

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   os   ar   使用   for   

背景

CURL在 a.php 中以 POST方式向 b.php 提交資料,但b.php無法接收到資料,而 CURL 操作顯示成功。

原來,"傳遞一個數組到CURLOPT_POSTFIELDS,CURL會把資料編碼成 multipart/form-data,而傳遞一個URL-encoded字串時,資料會被編碼成 application/x-www-form-urlencoded"。但是在使用 PHP Curl進行Post時可以指定 multipart/form-data 或 application/x-www-form-urlencoded 的方法。

 

驗證過程

樣本:

<?ph$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $data);curl_exec($ch);curl_close($ch);

 

這段代碼提交的Content-Type到底是multipart/form-data還是application/x-www-form-urlencoded呢?
tcpdump 抓包, wireshark 分析包內容,發現Content-Type的類型取決於$data的資料類型。

1、如果$data是字串,則Content-Type是application/x-www-form-urlencoded。
HTML Form URL Encoded: application/x-www-form-urlencoded
Form item: "uname" = "nickname"
Key: uname
Value: nickname

2、如果$data是k=>v的數組,則Content-Type是multipart/form-data,
set boundary
Content-Type: multipart/form-data; boundary=----------------------------749c186646f5\r\n

3、special case:
if pass an array array(‘uname‘ => ‘nickname‘, ‘uid‘ => 123456789) to CURLOPT_POSTFIELDS and set the content-type:application/x-www-form-urlencode to CURLOPT_HTTPHEADER
an unexpected result will be happened

[_POST] => Array([------------------------------635248b8d641Content-Disposition:_form-data;_name] => "uname"nickname------------------------------635248b8d641Content-Disposition: form-data; name="uid"123456789------------------------------635248b8d641--)

 

總結

header 可以設定對 http body data 的編碼方式

CURL_POST:TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.

application/x-www-form-urlencoded form元素預設指定的enctype屬性
multipart/form-data 上傳大量文本,包含非 ASCII字元或者位元據。既支援發送文本資料,也支援位元據上傳。Browser端<form>表單的ENCTYPE屬性值為multipart/form-data,它告訴我們傳輸的資料要用到多媒體傳輸協議,由於多媒體傳輸的都是大量的資料,所以規定上傳檔案必須是post方法,<input>的type屬性必須是file。

php curl POST 編碼方式 multipart/form-data與application/x-www-form-urlencode的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.