Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get PUT request body

Tags:

json

rest

php

I'm currently developing a Restful Json-API in PHP. I want to send a PUT-Request to items/:id to update a record. The data will be transferred as application/json.

I want to call the API with

curl -H "Content-Type: application/json" -X PUT -d '{"example" : "data"}' "http://localhost/items/someid"

On the server side, I'm not able the retrieve the request body. I tried

file_get_contents("php://input");

but this returns an empty string. Also a fopen()/fread() combination doesn't work.

When calling via POST, everything works great, I can read the json perfectly on the server side. But the API isn't Restful anymore. Does anyone have a solution for this? Is there another way to send and receive Json?

btw, I'm developing the API with the Slim Framework.

like image 359
aladin Avatar asked Mar 13 '12 12:03

aladin


2 Answers

php://input is only readable once for PUT requests:

Note: A stream opened with php://input can only be read once; the stream does not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND.

http://php.net/manual/en/wrappers.php.php

The Slim framework already reads the data upon request. Take the data from the Request object, into which it has been read.

like image 85
deceze Avatar answered Sep 19 '22 10:09

deceze


On the server side, I'm not able the retrieve the request body. I tried file_get_contents("php://input");

You can only use file_get_contents( 'php://input', 'r' ); once per request. Retrieving its values will truncate the values as well, so if you call it twice, it'll return an empty string. Slim's request object contains the values you need, so:

<?php
$app = new Slim( );

$app->put( '/items/someid', function () use ( $app ) {
    echo $app->request( )->put( 'example' ); // should display "data".
});
like image 42
Berry Langerak Avatar answered Sep 18 '22 10:09

Berry Langerak