john john - 4 months ago 4
PHP Question

Sending/Receiving PUT requests with PHP, having trouble parsing the request body?

I'm trying to build out a RESTful APi.

I'm sending a PUT request as so: /api/customer/1

$data['name'] = 'test';

$ch = curl_init('myurl/api/'.$name);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$results = json_decode(curl_exec($ch));


I am passing the $data list in the POSTFIELDS, which I assume will be in the request body.

When I go to parse, I am trying:

$params = file_get_contents('php://input');


However, I am not seeing the variable I passed in anywhere.

Any advice would be helpful, thank you.

Answer

The value of $params = file_get_contents('php://input'); will be a string you need to use parse_str:

$input = file_get_contents('php://input');
parse_str($input, $params);
print_r($params);

Also note in some cases php://input can only be read once so you might have to store it.

Comments