无法在"put"方法中读取REST请求数据

Igo*_*gor 7 php api rest json curl

我正在尝试使用PHP开发RESTful API而不使用框架.处理请求时,无法使用以下方法读取客户端数据:parse_str(file_get_contents("php://input"), $put_vars);

这是完整的代码:

public static function processRequest() {

    //get the verb
    $method = strtolower($_SERVER['REQUEST_METHOD']);

    $request = new Request();

    $data = array();
    $put_vars = array();

    switch ($method) {
        case 'get':
            $data = $_GET;
            break;
        case 'post':
            $data = $_POST;
            break;
        case 'put':
            parse_str(file_get_contents("php://input"), $put_vars);
            $data = $put_vars;
            echo $data;
            break;
    }

    $request->setMethod($method);
    $request->setRequestVars($data);

    if (isset($data['data'])) {
        $request->setData(json_decode($data));
        echo 'data exists';
    }

    return $request;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用cURL来休息API,当我输入这个命令时:curl -i -X PUT -d '{"name":"a","data":"data1"}' http://localhost/my-rest-api/api/我只能得到这个:

Array""

为什么没有返回正确的数据?

编辑

我还测试了另一段应该是API 的代码,file_get_contents('php://input', true)但仍然返回null.可能是网络服务器有问题吗?

Shi*_*nko 16

所述parse_str用于分析一个查询字符串(在形式ARG1 = XYZ&ARG2 = ABC),而不是JSON.您需要使用json_decode来解析JSON字符串.

$data = json_decode(file_get_contents("php://input"), true);
Run Code Online (Sandbox Code Playgroud)

这是有效的代码:

$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);
Run Code Online (Sandbox Code Playgroud)

卷曲命令:

curl -i -X PUT -d '{"name":"a","data":"data1"}' http://my-server/my.php
Run Code Online (Sandbox Code Playgroud)

响应:

array(2) {
  ["name"]=>
  string(1) "a"
  ["data"]=>
  string(5) "data1"
}
Run Code Online (Sandbox Code Playgroud)

  • @Igor如果通过POST发送JSON数据,则也不会解析为$ _POST。您需要做的是将请求的HTTP Content标头设置为application / json,这样PHP不会尝试将数据解析为查询字符串,然后您需要将json_decode原始输入数据作为建议在这里。这适用于您通过JSON发送数据的任何情况。 (2认同)