将php://input的内容存储到变量中

4

我正在尝试编辑和调整别人用PHP编写的REST服务器。它基于Phil Sturgeon编写的REST Server。基本上已经理解了所有内容,但我的请求没有按预期工作。

在服务器构造函数中是代码:

switch ($this->request->method)
{
    case 'post':
    $this->_post_args = $_POST;
    $this->request->format and $this->request->body = 
                                    file_get_contents('php://input');
    break;
}

我知道php://input只能被读取一次,所以在设置变量之前执行var_dump(file_get_contents('php://input'))会显示我的XML数据已经从输入流中正确读取,但是变量显然没有正确设置。
但是执行var_dump($this->request->body)仅输出null!有没有特殊的技巧来将php://input的内容存储到变量中?
编辑:
我正在使用API Kitchen发送POST请求,它发送的标头为
Status: 200
X-Powered-By: PHP/5.3.2-1ubuntu4.11
Server: Apache/2.2.14 (Ubuntu)
Content-Type: application/xml
Date: Fri, 10 Feb 2012 11:00:43 GMT
Keep-Alive: timeout=15, max=100
Content-Length: 936
Connection: Keep-Alive

我无法从这里看出编码方式是什么。
编辑3:
编码方式是application/x-www-form-urlencoded,这可能是问题所在!我如何明确指定它应该是什么?
编辑2: $this->request->method包含'post'

$this->request 是什么类型的对象? - Shiplu Mokaddim
我找不到单独的实现或任何东西,它第一次被设置是在同一个构造函数中,并且使用 $this->request->method = $this->_detect_method(); 进行设置。很抱歉我似乎没有提供太多帮助! - Josh
1
通过插入打印语句进行调试,并拆分复合语句。 - Shiplu Mokaddim
将变量分别转储打印会为两者都打印“NULL”,而当使用“var_dump($this->request->format and $this->request->body);”时,会打印“bool(false)”。 - Josh
1
php://inputmultipart/formdata 中无法使用,但您提到这不是问题。然后您说 $this->request->format 打印出 NULL,实际上相当于执行了类似于 null and $a = 1; 的操作,这意味着 $a = ...; 部分根本没有被执行! - Salman A
显示剩余2条评论
2个回答

4

感谢您所提供的帮助。事实证明,为了正常工作,请求的内容类型必须是application/xml,而不是之前错误的application/x-www-form-urlencoded。


1
如果$this->request->format的值为falseNULL0,则and运算符的后半部分不会被执行。
  $this->request->format and $this->request->body = file_get_contents('php://input');
                             ^
                             |
                             +--- this part wont execute

你应该这样写

if($this->request->format){
    $this->request->body = file_get_contents('php://input');
}

这有助于调试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接