form enctype的三种格式

以前没有注意过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源码:

<html>
<title>zc_POST_test</title>
<body>
<?php
$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;
?>
<br>POST test<br>
<a href="<?=$_SERVER['PHP_SELF'];?>">application/x-www-form-urlencoded</a>&nbsp;<a href="<?=$_SERVER['PHP_SELF'];?>?t=1">multipart/form-data</a>&nbsp;<a href="<?=$_SERVER['PHP_SELF'];?>?t=2">text/plain</a><br>
<form method="POST" name="webauthform"  enctype="<?php echo $form_type;?>" id="webauthform" action="<?=$_SERVER['REQUEST_URI'];?>">
title:&nbsp;&nbsp;<input type="text" name="title"><br>
content:<textarea name="content" cols="40" rows="10"></textarea>&nbsp;&nbsp;
<input type=submit name="submit" value="post article"><br>
<?php
if(!empty($_POST['submit']) )
{
echo "<br>POST:<br>";
print_r($_POST);
}
if( !empty($HTTP_RAW_POST_DATA)){
echo "<br>HTTP_RAW_POST_DATA: text/plain<br>";
print_r($HTTP_RAW_POST_DATA);
}
?>
</form>
</body>
</html>
</pre>
| 0个评论