post提交数据的常见方式及php对应的接收方法

post提交数据的方式,主要体现在http协议头上的Content-Type字段,不同的Content-Type对应不同的http请求体,与之相应的php接收数据方法也不同。

1.application/x-www-form-urlencoded

1.1发送

html中的form表单,如果不设置enctype属性,就默认用该方式提交数据。
发送的http请求类似:

POST http://example.com/testapi HTTP/1.1
Content-Length: 25
Content-Type: application/x-www-form-urlencoded

name=ball%E7%90%83&age=99

数据以kv对形式存并进行了urlencode,多个kv以&连接。比如上面的请求,实际发送的数据就是

name=ball%E7%90%83&age=99

1.2接收

可以使用$_POST获取数据。
例:

var_dump($_POST);
//得到结果
array(2) {
  ["name"]=>
  string(7) "ball球"
  ["age"]=>
  string(2) "99"
}

2.multipart/form-data

2.1发送

html中的form也可以设置这种方式上传数据。还是1中的数据,如果用该方式发送,则请求类似:

POST http://example.com/testapi HTTP/1.1
Content-Length: 234
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary6XncMq0p32KiFnlE

------WebKitFormBoundary6HL7YGChzJuy0cBX
Content-Disposition: form-data; name="name"

------WebKitFormBoundary6XncMq0p32KiFnlE
Content-Disposition: form-data; name="name"

ball球
------WebKitFormBoundary6XncMq0p32KiFnlE
Content-Disposition: form-data; name="age"

99
------WebKitFormBoundary6XncMq0p32KiFnlE--

注意:数据并未进行urlencode

2.2接收

可以使用$_POST获取数据。
例:

var_dump($_POST);
//得到结果
array(2) {
  ["name"]=>
  string(7) "ball球"
  ["age"]=>
  string(2) "99"
}

2.3why?

上例可以看到,同样是发送name,age,使用multipart/form-data请求要大了很多,那么该方式存在的意义是什么呢?

  1. 发送文件时,必须使用该方式。关于php如何接收上传的文件,可以点击这里查看详情

  2. 我们注意到,application/x-www-form-urlencoded方式会对数据进行urlencode而multipart/form-data则不会。所以如果发送大段汉字时,使用后者可能会让请求长度变小。

3.raw

3.1 发送

对应的content-type有application/json,text/plain等,都是将一段文本直接发给服务端。服务端的接收方式也相同,所以将其归为一类。这些方式无法通过html的form形式发送。
比如:

POST http://example.com/testapi HTTP/1.1
Content-Length: 27
Content-Type: application/json

{"name":"ball球","age":99}

body中是一段json数据,但你也可以使用text/plain发送该数据,对于php服务端来说并没有特别的影响,只是使用application/json更符合规范。

3.2 接收

可以使用php://input接收数据

$c = file_get_contents("php://input"); 
echo $c;
var_dump(json_decode($c, true));

//得到结果
{"name":"ball球","age":99}
array(2) {
  ["name"]=>
  string(7) "ball球"
  ["age"]=>
  int(99)
}

注意:早先的php版本,还可以从$GLOBALS[‘HTTP_RAW_POST_DATA’]获取数据,但php7之后,不再支持这种方式。

四.总结

发送 接收
application/x-www-form-urlencoded $_POST
multipart/form-data(数据) $_POST
multipart/form-data(文件) $_FILES
raw php://input

猜你喜欢

转载自blog.csdn.net/qmhball/article/details/87866373