How do I get the request body?
I am trying to implement a simple JSON-RPC server. The client part is handled by the jquery.jsonrpc. This seems to work fine, sending a JSON-RPC message as the payload of a post message.
My JSON-RPC 'server' currently just wants to echo the data so I can see the result in the FireBug http response.
The code is this:
<?php
class jsonrpc {
var $requestData;
function jsonrpc() {
if (isset($_SERVER["REQUEST_URI"]) && isset($_SERVER["REQUEST_METHOD"])) {
if (isset($_SERVER["CONTENT_LENGTH"]) && $_SERVER["CONTENT_LENGTH"] > 0) {
$this->requestData = "";
$httpContent = fopen("php://input", "r");
echo "httpcontent=".$httpContent;
while ($data = fread($httpContent, 1024)) {
$this->requestData .= $data;
}
fclose($httpContent);
}
}
echo "jsonrpc::jsonrpc()\n";
}
}
?>
And the Response tab shows:
POST http://api.localhost/index.php?tm=1317246797964 200 OK 6ms
<br />
<b>Warning</b>: fopen("php://input", "r") - No error in <b>C:\Develop\ZeroSumGames\api\htdocs\rpc.php</b> on line <b>9</b><br />
httpcontent=<br />
<b>Warning</b>: fread(): supplied argument is not a valid File-Handle resource in <b>C:\Develop\ZeroSumGames\api\htdocs\rpc.php</b> on line <b>11</b><br />
<br />
<b>Warning</b>: fclose(): supplied argument is not a valid File-Handle resource in <b>C:\Develop\ZeroSumGames\api\htdocs\rpc.php</b> on line <b>14</b><br />
jsonrpc::jsonrpc()
Object { error="Internal server error", version="2.0"}
I can see there is data there because on the FireBug request headers tab I can see this:
Host api.localhost
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13
Accept application/json, text/javascript, */*
Accept-Language en-gb,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Content-Type application/json; 开发者_高级运维charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://api.localhost/index.html
Content-Length 72
And also I can see this on the post tab:
{"jsonrpc":"2.0","method":"example.method.name","id":1,"params":[1,2,3]}
My server is too old for file_get_contents (4.2.2) but the replacement functions I have found on the net internally do the same as what I have written above (more or less) and also have the issue regarding opening of php://input
.
So my question is why can't I open php://input for reading?
I upgraded my local machine to 4.4.2 and that works fine so I guess it is a bug in 4.2.2. Not quite the fix I was hoping for.
精彩评论