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
.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- Carriage Return (ASCII chr 13) is missing from tex
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
Simple example of how to use it
php://input
can give you the raw bytes of the data. This is useful if the POSTed data is a JSON encoded structure, which is often the case for an AJAX POST request.Here's a function to do just that:
The
$_POST
array is more useful when you're handling key-value data from a form, submitted by a traditional POST. This only works if the POSTed data is in a recognised format, usuallyapplication/x-www-form-urlencoded
(see http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 for details).The reason is that
php://input
returns all the raw data after the HTTP-headers of the request, regardless of the content type.The PHP superglobal
$_POST
, only is supposed to wrap data that is eitherapplication/x-www-form-urlencoded
(standard content type for simple form-posts) ormultipart/form-data-encoded
(mostly used for file uploads)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).
So, if you simply POST a good old HTML
form
, the request looks something like this: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:
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).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 notmultipart/form-data
-encoded).This is also how you would access XML-data or any other non-standard content type.
If post data is malformed, $_POST will not contain anything. Yet, php://input will have the malformed string.
For example there is some ajax applications, that do not form correct post key-value sequence for uploading a file, and just dump all the file as post data, without variable names or anything. $_POST will be empty, $_FILES empty also, and php://input will contain exact file, written as a string.