【问题标题】:Reading json input in php在php中读取json输入
【发布时间】:2013-08-24 16:05:38
【问题描述】:

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

$_POST 适用于 key-value 对类型的输入,例如 form-data 或 x-www-urlencoded

key1=value1&key2=value2&key3=value3

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

喜欢{'key1':'value1','key2':'value2','key3':'value3'}

这无法使用$_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;
    }
}

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

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

还有其他方法可以读取php中的json输入吗?

【问题讨论】:

  • 首先要检查,php 版本是否相同,是否设置了allow_fopen_url
  • __construct() 中尝试var_dump($this->json_input_data )
  • @RohanKumar -> 它在我托管的服务器中打印“NULL”。在 localhost 中打印 "array(2) { ["id"]=> string(2) "79" ["t"]=> string(5) "22_00" }"。
  • @DevZer0 PHP 版本是 5.3,它支持。我没有在我的控制面板中找到访问 php.ini 文件的选项(它是共享服务器)。有什么方法可以测试吗?请帮助..

标签: php json codeigniter rest


【解决方案1】:

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

谨慎使用 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

【讨论】:

    【解决方案2】:

    php://input 是一个只读流,允许您读取原始数据 从请求正文。在 POST 请求的情况下,最好 使用 php://input 而不是 $HTTP_RAW_POST_DATA 因为它没有 依赖于特殊的 php.ini 指令。此外,对于那些情况 $HTTP_RAW_POST_DATA 默认不填充,它是一个潜在的 激活时内存占用较少的替代方案 always_populate_raw_post_data。 php://input 不适用于 enctype="multipart/form-data"

    wrappers

    也试试这个,

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

    【讨论】:

    • 我看到了包装器,而且输入不是 enctype="multipart/form-data"。它在 localhost 中运行良好,但是当我使用 php://input 时,我用来托管的 Web 服务器返回 null。可能是它拒绝访问。我想知道是否可以用任何其他方法来做???
    • 它在我托管的服务器中给出“NULL”。在 localhost 中打印 "array(2) { ["id"]=> string(2) "79" ["t"]=> string(5) "22_00" }"。在问题的cmets中提到了它。我认为在该 Web 服务器中无法访问“php://input”。
    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多