以前没有注意过enctype的各个属性在底层有什么不一样。
工作关系,最近分析了下form enctype,首先说application/x-www-form-urlencoded
此种类型是默认的,及时在form属性中不设置enctype,HTTP报文中的结构:
POST /post_test.php HTTP/1.1
Accept-Language: zh-CN
User-Agent: Mozilla/4.0
Content-Type: application/x-www-form-urlencoded
Host: 192.168.12.102
Content-Length: 42
Connection: Keep-Alive
Cache-Control: no-cache
title=test&content=%B3%AC%BC%B6%C5%AE%C9%FA&submit=post+article
可以看到,表单上传后,最终是通过URL转码后,拼接到一起的。
而multipart/form-data,以boundary=为区分,假如还有文件的话,会分多次请求。
这个类型,是包含文件上传表单的必须设置的。
POST /post_test.php?t=1 HTTP/1.1
Accept-Language: zh-CN
User-Agent: Mozilla/4.0
Content-Type: multipart/form-data; boundary=---------------------------7dbf514701e8
Accept-Encoding: gzip, deflate
Host: 192.168.12.102
Content-Length: 345
Connection: Keep-Alive
Cache-Control: no-cache
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="title"
test
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="content"
....
-----------------------------7dbf514701e8
Content-Disposition: form-data; name="submit"
post article
-----------------------------7dbf514701e8--
最后一种: text/plain,这种类型基本是不使用的。HTTP报文中,不包含任何格式。php使用$_POST数组取不到值。必须使用$HTTP_RAW_POST_DATA才能获取到。
POST /post_test.php?t=2 HTTP/1.1
Accept-Language: zh-CN
User-Agent: Mozilla/4.0
Content-Type: text/plain
Accept-Encoding: gzip, deflate
Host: 192.168.12.102
Content-Length: 51
Connection: Keep-Alive
Cache-Control: no-cache
title=test
content=........
submit=post article
附上测试的php源码:
zc_POST_test$form_type = 'application/x-www-form-urlencoded';
if(!empty($_GET['t'])){
switch($_GET['t']){
case '1':$form_type = 'multipart/form-data';break;
case '2':$form_type = 'text/plain';break;
}
}
echo $form_type;
?>
POST test
application/x-www-form-urlencoded multipart/form-data text/plain
title:
content:
if(!empty($_POST['submit']) )
{
echo "
POST:
";
print_r($_POST);
}
if( !empty($HTTP_RAW_POST_DATA)){
echo "
HTTP_RAW_POST_DATA: text/plain
";
print_r($HTTP_RAW_POST_DATA);
}
?>