file_get_contents("php://input")
or $HTTP_RAW_POST_DATA
- which one is better to get the body of JSON request?
And which request type (GET
or POST
) should I use to send JSON data when using client side XmlHTTPRequest
?
My question was inspired from this answer: How to post JSON to PHP with curl
Quote from that answer:
From a protocol perspective
file_get_contents("php://input")
is actually more correct, since you're not really processing http multipart form data anyway.
file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :
send by post JSON string
1.php
For JSON data, it's much easier to POST it as "application/json" content-type. If you use GET, you have to URL-encode the JSON in a parameter and it's kind of messy. Also, there is no size limit when you do POST. GET's size if very limited (4K at most).
Source: http://php.net/manual/en/wrappers.php.php.
Your second question is easy, GET has a size limitation of 1-2 kilobytes on both the server and browser side, so any kind of larger amounts of data you'd have to send through POST.
Actually
php://input
allows you to read raw POST data.It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives.
php://input
is not available withenctype="multipart/form-data"
.Reference: http://php.net/manual/en/wrappers.php.php
The usual rules should apply for how you send the request. If the request is to retrieve information (e.g. a partial search 'hint' result, or a new page to be displayed, etc...) you can use GET. If the data being sent is part of a request to change something (update a database, delete a record, etc..) then use POST.
Server-side, there's no reason to use the raw input, unless you want to grab the entire post/get data block in a single go. You can retrieve the specific information you want via the _GET/_POST arrays as usual. AJAX libraries such as MooTools/jQuery will handle the hard part of doing the actual AJAX calls and encoding form data into appropriate formats for you.