I have a switch
based on $_SERVER['REQUEST_METHOD']
and something is going wrong in the PUT
case. The plausible way to read PUT
is to use php://input
and read it with fopen
or file_get_contents
.
The data that gets sent to PUT is of 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. The data gets filled and my putData()
handles everything just fine. The problem is that I need to accept JSON in this case, how do I go about? My REST client throws an empty array when I var_dump($putData)
.
Try using json_decode instead of 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. Try removing var_dump()
Also, I'm pretty sure you must call http_response_code()
before any output is sent to the client.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.