Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading json input in php

php://input is working properly in localhost. But in server it returns empty. Input( request ) to my site is a json(REST - application/json type), so $_POST didn't work ( please read This question ) .

$_POST works with key-value pair type inputs like form-data or x-www-urlencoded

key1=value1&key2=value2&key3=value3

I'm using application/json as input (in REST).

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

This can't be handled using $_POST. But using php://input can help to read that 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;
    }
}

Above code is works fine in another webserver also, But not in the current one. :(

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

Is there is any other methods to read json input in php ?

like image 368
Arjun Raj Avatar asked Aug 22 '13 04:08

Arjun Raj


1 Answers

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

See wrappers

Try this too,

....
  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 for allow_url_fopen.

like image 152
Rohan Kumar Avatar answered Oct 06 '22 14:10

Rohan Kumar