Daniel Daniel - 29 days ago 8
HTTP Question

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

I'm building API with the following structure:


  • method
    POST

  • uri
    /words
    .

  • body
    {"word":"example"}
    .



This request should add word to database and if I testing it by
httpie
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"
}
}


In
test
I placed variable obtained in
php
by:

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'),true);
$post = $_POST;


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

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


I obtain the following console log:

{
"test":{
"method":"POST",
"input":null,
"post":{
"word":"word from form"
}
},
"words":{
"id":"581f34b28b0414307476f7b6",
"word":null
}
}


Now
input
is empty. Word is null because I am processing
$input["word"]
, from
php://input
. My questions:


  • Should I process
    $_POST
    , or check both variable?

  • How about best practices of using these methods?

  • Can I send
    php://input
    from browser or
    $_POST
    from command line toll like
    httpie
    ?


Answer

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'
Comments