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_contents("php://input"), $put_vars);
Here's the full code:
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;
}
I'm using cURL to rest the API and when I type this command: curl -i -X PUT -d '{"name":"a","data":"data1"}'
http://localhost/my-rest-api/api/
I only get this back:
Array""
Why isn't the proper data returned?
EDIT
I also tested another piece of code that is supposed to be an API and file_get_contents('php://input', true)
still returns null. Could it be that there's something wrong with the web server?
Actually yes. After banging my head on this for a few hours, I found that the culprit for the missing data was this:
Another piece of code was accessing the php://input before my code, and on servers with php < 5.6, this caused the input to be lost.
Only on PUT requests that is.
The
parse_str
is used to parse a query string(in form arg1=xyz&arg2=abc) and not JSON. You need to usejson_decode
to parse JSON strings.Here is the code that works:
Curl command:
Response: