正在读取php中的json输入


Reading json input in php

php://input在localhost中正常工作。但在服务器中,它返回为空。我的站点的输入(请求)是jsonREST-application/json类型),所以$_POST不起作用(请阅读此问题)。

$_POST适用于键值对类型的输入,如表单数据或x-www-urlended

key1=value1&key2=值2&key3=值3

我使用application/json作为输入(在REST中)。

类似{‘key1’:‘value1’,‘key2’:‘value 2’,‘key 3’:‘Value 3’}

使用$_POST无法处理此问题。但是使用php://input可以帮助读取这些数据。

我的代码

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;
    }
}

上面的代码在另一个Web服务器中也可以正常工作,但在当前的Web服务器中不行。:(

我认为我的web服务器拒绝访问php://input

有没有其他方法可以读取php中的json输入

php://input是一个只读流,允许您读取原始数据来自请求主体。在POST请求的情况下,最好使用php://input而不是$HTTP_RAW_POST_DATA,因为它不是取决于特殊的php.ini指令。此外,对于那些默认情况下不会填充$HTTP_RAW_POST_DATA,它可能是较少占用内存的激活替代方案always_popuple_raw_post_dataphp://input不适用于enctype="多部分/表单数据"

参见包装

试试这个吧,

....
  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';
  }
....

同时检查allow_url_fopen

我知道这是旧的,但它可能会帮助其他人:

小心json中的单引号

来自关于json_decode的PHP文档:

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