Daniel Daniel - 1 year ago 92
HTTP Question

Shoul I use `php://input` and/or `$_POST`?

I'm building API with the following structure:

  • method

  • uri

  • body

This request should add word to database and if I testing it by
everything is ok.

$ http POST localhost:8000/words word="new word2"

HTTP/1.1 200 OK
Access-Control-Allow-Headers: application/json
Access-Control-Allow-Origin: http://localhost:8080
Connection: close
Content-Type: application/json
Host: localhost:8000
X-Powered-By: PHP/7.0.12-1+deb.sury.org~xenial+1
"test": {
"method": "POST",
"input": {
"word": "new word2"
"post": []
"words": {
"id": "581f2f118b0414307476f7b3",
"word": "new word2"

I placed variable obtained in

$input = json_decode(file_get_contents('php://input'),true);
$post = $_POST;

We can see that
is empty. If I use javascript:

$(form).submit(function(e) {
var url = "http://localhost:8000/words";
var data = {"word" : form.elements["word"].value };
type: "POST",
url: url,
data: data,
dataType: 'json',
success: function(data)

I obtain the following console log:

"word":"word from form"

is empty. Word is null because I am processing
, from
. My questions:

  • Should I process
    , or check both variable?

  • How about best practices of using these methods?

  • Can I send
    from browser or
    from command line toll like

Answer Source

Your manually constructed example and your JavaScript example are not equivalent.

In the first you are sending JSON encoded data with an application/json content-type.

In the second, you are passing a JavaScript object to jQuery and allowing it to follow it's default behaviour, which is to encod it using the application/x-www-form-urlencoded format and use that as the content type (just like submitting a regular HTML form would do).

PHP supports application/x-www-form-urlencoded data in POST requests, but not JSON.

Should I process $_POST, or check both variable?

If you are sending application/x-www-form-urlencoded data or another format supported by PHP, then use $_POST. Otherwise you need to get the raw data from php://input and parse it yourself.

Can I send php://input from browser

See POST data in JSON format

$_POST from command line toll like httpie?

See the httpie documentation:

http --form POST api.example.org/person/1 name='John Smith'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download