Reading json input in php

php://input works correctly in localhost. But on the server, it returns empty. The input (request) to my site is json (REST - application / json type), so $_POST did not work (please read this question ).

$ _ POST works with key-value pair inputs such as form data or x-www-urlencoded

key1 = value1 & key2 = value2 & key3 = value3

I use application/json as input (in REST ).

Like {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

This is not possible with $_POST . But using php://input can help read this data.

My code

 class Webservice_Controller extends CI_Controller { public $json_input_data; public function __construct(){ parent::__construct(); $this->json_input_data = json_decode(file_get_contents('php://input'),TRUE); } public function json_input($label){ if(isset($this->json_input_data[$label])) return $this->json_input_data[$label]; else return NULL; } } 

The above code works fine on another web server, but not in the current one :(

I think my web server is denying access to php://input .

Are there any other methods for reading json input in php?

+6
source share
2 answers

php: // input - a read-only stream that allows you to read the source data from the request authority. In the case of POST requests, it is preferable to use the php: // input instead of $ HTTP_RAW_POST_DATA, since it does not depend on special php.ini directives. Moreover, for cases when $ HTTP_RAW_POST_DATA is not populated by default, this is a potentially less energy-intensive alternative to always_populate_raw_post_data activation. php: // input unavailable with ENCTYPE = "multipart / form data" .

See wrappers

Try also

 .... public function __construct(){ parent::__construct(); if(isset($_POST)) { var_dump(file_get_contents('php://input')); $this->json_input_data=json_decode(file_get_contents('php://input'),TRUE); } else echo 'Not Post'; } .... 

Also check allow_url_fopen .

+2
source

I know this is old, but it may help others:

Caution with single quotes inside json

From the PHP documentation about json_decode:

 the name and value must be enclosed in double quotes single quotes are not valid $bad_json = "{ 'bar': 'baz' }"; json_decode($bad_json); // null 
+2
source

Source: https://habr.com/ru/post/952252/


All Articles