PHP“php://输入"对比 $_POST [英] PHP "php://input" vs $_POST
问题描述
我被指示在与来自 JQuery 的 Ajax 请求交互时使用方法 php://input
而不是 $_POST
.我不明白的是使用这个与 $_POST
或 $_GET
的全局方法的好处.
I have been directed to use the method php://input
instead of $_POST
when interacting with Ajax requests from JQuery. What I do not understand is the benefits of using this vs the global method of $_POST
or $_GET
.
推荐答案
原因是 php://input
返回请求的 HTTP-headers 之后的所有原始数据,无论内容类型.
The reason is that php://input
returns all the raw data after the HTTP-headers of the request, regardless of the content type.
PHP 超全局$_POST
,只有应该包装数据是
The PHP superglobal $_POST
, only is supposed to wrap data that is either
application/x-www-form-urlencoded
(简单表单帖子的标准内容类型)或multipart/form-data
(主要用于文件上传)
application/x-www-form-urlencoded
(standard content type for simple form-posts) ormultipart/form-data
(mostly used for file uploads)
这是因为只有这些内容类型必须得到用户代理的支持.因此,服务器和 PHP 传统上不希望接收任何其他内容类型(这并不意味着它们不能).
This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don't expect to receive any other content type (which doesn't mean they couldn't).
所以,如果你只是 POST 一个很好的旧 HTML form
,请求看起来像这样:
So, if you simply POST a good old HTML form
, the request looks something like this:
POST /page.php HTTP/1.1
key1=value1&key2=value2&key3=value3
但如果你经常使用 Ajax,这个问题还包括用类型(字符串、整数、布尔)和结构(数组、对象)交换更复杂的数据,所以在大多数情况下 JSON 是最好的选择.但是带有 JSON 有效负载的请求看起来像这样:
But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:
POST /page.php HTTP/1.1
{"key1":"value1","key2":"value2","key3":"value3"}
内容现在是 application/json
(或者至少没有上面提到的),所以 PHP 的 $_POST
-wrapper 不知道如何处理(然而).
The content would now be application/json
(or at least none of the above mentioned), so PHP's $_POST
-wrapper doesn't know how to handle that (yet).
数据仍然存在,只是无法通过包装器访问它.所以你需要自己用 file_get_contents('php://input')
(只要它不是 multipart/form-data
-encoded).
The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input')
(as long as it's not multipart/form-data
-encoded).
这也是您访问 XML 数据或任何其他非标准内容类型的方式.
This is also how you would access XML-data or any other non-standard content type.
这篇关于PHP“php://输入"对比 $_POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!