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

使用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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器