john john - 6 months ago 13
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_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.


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);

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