Get PUT params with Slim PHP
Asked Answered
P

2

14

I searched, but I didn't find an answer. I have a RESTful API to manage a basic CRUD. I'm trying to create an update method using PUT, but I can't retrieve the params values. I'm using Postman to make the requests, my request looks like:

URL

http://localhost/api/update/987654321

Params

id = 987654321
name = John Smith
age = 35

PHP

$app = new Slim();
$app->put('/update/:id', function( $id ) use( $app ){
    var_dump([
        'id' => $id,
        'name' => $app->request->put('name'),
        'age' => $app->request->put('age')
    ]);
});

My var_dump() result is:

array(3) {
  ["id"]=>
  string(9) "987654321"
  ["name"]=>
  NULL
  ["age"]=>
  NULL
}

What is wrong? Any idea?

Pardon answered 20/5, 2014 at 13:38 Comment(3)
checkout the manual docs.slimframework.com/#Request-Body if you scroll down to the Request Variables section there is an example there. Alternatively you can take the parameters directly from the body and put into var by doing parse_str(file_get_contents("php://input"),$post_vars);Mongoose
I want to upload images in this request. Using POST to update is a bad pratice?Pardon
sorry my comment wasn't about POST data, i copied the code from another site. However the PUT data is set in the body of the request just like with all other types of request apart from GET (although you might be able to attach a body string to a GET request, I've never tried it). You could do parse_str($app->request->getBody(), $vars); and do a var_dump on that to see your data.Mongoose
T
23

I had the same problem. Firstly, I was sending PUT data with the Postman option to encode it as "form-data", that's why Slim wasn't getting the param values.

As it is explained in W3, the content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

In our case, we have to send PUT data with the Postman option "x-www-form-urlencoded" (see explanation of "application/x-www-form-urlencoded" in W3).

Screenshot of the right Postman option selected

Trigraph answered 5/11, 2014 at 8:33 Comment(3)
Switched to x-www-form-urlencoded with postman to make it works ! Thanks for the well explained answer (w3 link)!Ferdinand
You just saved me hours of head bashing. Thank you!Capriola
I have a question, with x-www-form-urlencoded cannot upload file, it's only accept the string. How can I upload a file using PUT/PATCH method..?Sarawak
P
1

$app->request->put() is returning a null value...

so u can use try $app->request->params instead

Petal answered 6/6, 2016 at 9:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.