I read a few questions on the topic here, but could not find the answer I'm looking for. I am making $ .post with jQuery on a PHP5.6 server.
$.post('/', {a:100, b:'test'}, function(data){ }, 'json');
Console Encoding
Content-Type application/x-www-form-urlencoded; charset=UTF-8
If I try to read POST data with regular $ _POST, PHP5.6 notifies me
PHP Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead
So, I tried the suggestion, added always_populate_raw_post_data = -1 in php.ini and
json_decode(file_get_contents("php://input"));
PHP5.6 warns me that it is invalid
PHP Warning: First parameter must either be an object or the name of an existing class
So, I threw file_get_contents ("php: // input"), and this is the line.
a=100&b="test"
So, I parsed the string and encoded, then decoded
parse_str(file_get_contents("php://input"), $data); $data = json_decode(json_encode($data)); var_dump($data);
AND THEN I finally got my $ data as an object, not an array, like a true JSON object.
I resorted to using $ _POST at the moment ... But then I'm curious about updating PHP.
The question is, is there a more direct solution to this, or does using file_get_contents ("php: // input") also mean parsing the syntax coding with the extension?
Edit: so it seems that this does not work on several json's levels. Consider the following:
{"a":100, "b":{"c":"test"}}
How sent to Ajax / Post
{a:100, b:{c:"test"}}
Performance
parse_str(file_get_contents("php://input"), $post); var_dump($post);
Will output
array(2) { ["a"]=>string(8) "100" ["b"]=>string(16) "{"c":"test"}" }
Or do (as suggested)
parse_str(file_get_contents("php://input"), $post); $post= (object)$post;
Will output
object(stdClass)#11 (2) { ["a"]=>string(8) "100" ["b"]=>string(16) "{"c":"test"}"
}
How to convert file_get_contents ("php: // input") to a true object with the same "architecture" without using a recursive function?
Edit2: My error, the proposed work, I got a side in the comments with JSON.stringify that caused the error. Bottom line: it works with json_decode (json_encode ($ post)) or $ post = (object) $ post;
Repeat using jQuery $ .post:
$.post('/', {a:100, b:{c:'test'}}, function(data){ }, 'json'); parse_str(file_get_contents("php://input"), $data); $data = json_decode(json_encode($data));
or
parse_str(file_get_contents("php://input"), $data); $data= (object)$data;
No need to use JSON.stringify