dscs63759
2015-01-18 14:58
浏览 216
已采纳

使用json内容类型的PUT请求

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).

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqu92800 2015-01-18 15:05
    已采纳

    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;
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douao7937 2015-01-18 15:01

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题