Yii 2.0: Automatic Parameter Binding to POST vars in Yii2

4 followers

I wrote about this on my blog, but wanted to post it here too.

I've been working a lot with the alpha of Yii2 recently and have been loving it, but have run into a few issues. I'm going to try to post them here as a help to those of you who may have the same issues down the line.

What is automatic parameter binding? If you read the Yii 1.1 guide to Controllers, you'll see that if you define an action with a parameter of $id, and then add a querystring of ?id=1 to your request, that parameter will automatically be bound to the $id parameter. It's a nice convenience. For some reason, Yii2 only automatically binds GET variables, not POST. I wanted restrict certain actions to POST verbs and pass data through and have it be automatically be bound. But it only binds GET vars. Dang.

It's super easy to fix, actually. All you have to do is intercept the runAction method in your controller of choice and do a little tweaking. Here's the code:

public function runAction($id, $params=array()){
    $params = array_merge($_POST, $params);
    parent::runAction($id, $params);
}

You can either add this to your particular controller that you'd like to automatically bind POST vars to, or you can create a base controller and extend all your other controllers off of that.

Total 2 comments

#16703 report it
MLF at 2014/03/21 04:52am
Simple fix for security breach (previous comment)

Just try this:

public function runAction($id, $params=array()){
    parent::runAction($id, array_merge($params, $_POST));
}

So, the Posted values are the last items take place in the final params array and therefore, it'll override the get values.

#15201 report it
redguy at 2013/10/17 10:38am
security breach

Your code causes application to become less secure, because you can easily override any POST parameter with one passed in GET. In extreme case you can pass all needed params with GET instead of POST, which may easily lead to CSRF vulnerability. This is also why Yii binds only GET params.

Whether application will be finally vulnerable or not depends on actions code of course, but still - it is much easier to overlook something and expose functionality to plain GET requests and further to CSRF...

Leave a comment

Please to leave your comment.