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;