26

I'm having problem with CSRF Validation in yii2. The validation works fine with the default form generated by the gii but when I edit the form with html tags then the form submission throws a bad request error. I have disabled csrf validation to hide the error but I want to use this for the security of the application and data validation.

Is there any way of solving this error or is there a way of configuring it to work correctly in this scenario?

Edd
  • 3,724
  • 3
  • 26
  • 33
msucil
  • 806
  • 1
  • 8
  • 15

2 Answers2

51

I guess, your html form doesn't have hidden _csrf field, which is automatically generated by standard Yii2 widgets.

So the minimum code of your custom form might be like this:

<form method="post">
    <input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
    <button type="submit"> Save </button>
</form>
arogachev
  • 33,150
  • 7
  • 114
  • 117
Pavel Bariev
  • 2,546
  • 1
  • 18
  • 21
  • I've only changed the form input element with custom html element and my form element include the csrf value with name that is generated by the gii. i don't know what's happening. – msucil Feb 12 '15 at 15:47
  • I have hidden _csrf param in my Yii2 form and autogenerated token as its value. But anyway my app.log is full of BadRequestHttpException entries, even though the form data is stored normally. What am I doing wrong and how to fix it? – mogilka Aug 07 '17 at 09:56
6

Try this

<?=yii\helpers\Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken)?>
Alex S
  • 719
  • 6
  • 8