REST request data can't be read in 'put' method

前端 未结 2 1322
北荒
北荒 2020-12-18 00:11

I\'m trying to develop a RESTful API with PHP without using frameworks. While processing the request, the client data cannot be read using this: parse_str(file_get_con

2条回答
  •  再見小時候
    2020-12-18 00:35

    The parse_str is used to parse a query string(in form arg1=xyz&arg2=abc) and not JSON. You need to use json_decode to parse JSON strings.

    $data = json_decode(file_get_contents("php://input"), true);
    

    Here is the code that works:

    $method = strtolower($_SERVER['REQUEST_METHOD']);
    $data = array();
    
    switch ($method) {
        case 'get':
            $data = $_GET;
            break;
        case 'post':
            $data = $_POST;
            break;
        case 'put':
            $data = json_decode(file_get_contents("php://input"), true);
            break;
    }
    
    var_dump($data);
    

    Curl command:

    curl -i -X PUT -d '{"name":"a","data":"data1"}' http://my-server/my.php
    

    Response:

    array(2) {
      ["name"]=>
      string(1) "a"
      ["data"]=>
      string(5) "data1"
    }
    

提交回复
热议问题