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 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题