3

How can I get "token" param from PUT request?

Controller:

public function actionUpdate()
{
    $params = Yii::$app->getRequest()->getBodyParams();
    return $params;
}

Request:

curl -X PUT -H "Authorization: Bearer LL_nACyYVJFJyuHJxcOtiXu3OVNBJ_xo" -F "token=12345" "http://localhost/api/v1/devices/1"

Response:

{"success":true,"data":{"--------------------------580af3364bd175a7\r\nContent-Disposition:_form-data;_name":"\"token\"\r\n\r\n12345\r\n--------------------------580af3364bd175a7--\r\n"}}r

I have tried this:

return $params['token'];

PHP Notice: Undefined index: token

And this

parse_str(file_get_contents("php://input"), $params);

Will return the same result

Alex Pavlov
  • 571
  • 1
  • 7
  • 24

2 Answers2

3

i think the problem is related to the content type of your request. getting body params from put/post requires Content-type: application/x-www-form-urlencoded

try using curl with -d instead of -F:

curl -X PUT -H "Authorization: Bearer LL_nACyYVJFJyuHJxcOtiXu3OVNBJ_xo" -d "token=12345" "http://localhost/api/v1/devices/1"
csminb
  • 2,382
  • 1
  • 16
  • 27
  • Yes, that's it. Thanks. I just used Postman and it changed Content-type by default in PUT request. – Alex Pavlov Jan 05 '17 at 04:35
  • I know it's an old post, but for those who come accross this again there's another solution. You can keep the Content-Type as application/json if you use AJAX but you need to add json parser to you request component. Here is the doc for it https://www.yiiframework.com/doc/guide/2.0/en/rest-quick-start (see Enabling JSON Input section). After that you'll be able to use any params from your request body – Konstantin Jul 04 '19 at 10:29
0

You could use Yii's MultipartFormDataParser. This allows you to use Yii::$app->request->post() or Yii::$app->request->getBodyParams() on PUT or DELETE requests, as you know it from POST requests.

You just need to configure it that it gets applied:

return [
    'components' => [
        'request' => [
            'parsers' => [
                'multipart/form-data' => 'yii\web\MultipartFormDataParser'
            ],
        ],
    ],
];

That's it.

robsch
  • 9,358
  • 9
  • 63
  • 104