[英]PUT request with json content-type
I have a switch
based on $_SERVER['REQUEST_METHOD']
and something is going wrong in the PUT
case. 我有一个基于
$_SERVER['REQUEST_METHOD']
的switch
,在PUT
情况下出了点问题。 The plausible way to read PUT
is to use php://input
and read it with fopen
or file_get_contents
. 读取
PUT
的合理方法是使用php://input
并通过fopen
或file_get_contents
读取。
The data that gets sent to PUT is of Content-type: application/json
发送到PUT的数据的
Content-type: application/json
Currently, this is the case I have got: 目前,这是我遇到的情况:
case "PUT":
parse_str(file_get_contents("php://input"), $putData);
var_dump($putData);
if(isset($_GET['id'])){
putData($_GET['id'], $putData);
} else {
print json_encode(["message" => "Missing parameter `id`."]);
http_response_code(400);
}
break;
The great thing is that my cURL request with key/value pairs work perfectly fine. 很棒的事情是我的带有键/值对的cURL请求工作得很好。 The data gets filled and my
putData()
handles everything just fine. 数据被填充,我的
putData()
处理一切都很好。 The problem is that I need to accept JSON in this case, how do I go about? 问题是在这种情况下我需要接受JSON,我该怎么办? My REST client throws an empty array when I
var_dump($putData)
. 当我
var_dump($putData)
时,我的REST客户端抛出一个空数组。
Try using json_decode instead of parse_str 尝试使用json_decode代替parse_str
case "PUT":
$rawInput = file_get_contents("php://input");
$putData = json_decode($rawInput);
if (is_null($putData)) {
http_response_code(400);
print json_encode(["message" => "Couldn't decode submission", "invalid_json_input" => $rawInput]);
} else {
if(isset($_GET['id'])){
putData($_GET['id'], $putData);
} else {
http_response_code(400);
print json_encode(["message" => "Missing parameter `id`."]);
}
}
break;
Just guessing here, but if your REST client accepts JSON for this request, it will choke on var_dump()
which outputs a string which isn't JSON right back onto the response. 只是在这里猜测,但是如果您的REST客户端接受此请求的JSON,它将阻塞
var_dump()
,后者将输出不是JSON的字符串直接返回到响应。 Try removing var_dump()
尝试删除
var_dump()
Also, I'm pretty sure you must call http_response_code()
before any output is sent to the client. 另外,我很确定您必须在将任何输出发送到客户端之前调用
http_response_code()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.