yii2 uses csrf to prevent repeated submission of forms
First, by default, yii2’s csrf verification Token verification is saved through cookies. To prevent repeated submission of forms, you must first change this method to session.
This can be achieved by modifying the project configuration(Recommended learning:yii framework)
'components' => [ 'request' => [ 'enableCsrfCookie' => false ] ]
Then, after the csrf verification is passed , the csrf token saved in the session will not be refreshed or cleared before entering the next get request, and the place to verify the csrf is in the beforeAction method of the controller. The source code yii\web\Controller is as follows
/** * @inheritdoc */ public function beforeAction($action) { if (parent::beforeAction($action)) { if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) { throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.')); } return true; } return false; }
Of course it is not good to change the source code, so create a new controller to inherit the controller and implement the beforeAction method
public function beforeAction($action) { if (parent::beforeAction($action)) { if ($this->enableCsrfValidation) { Yii::$app->getRequest()->getCsrfToken(true); } return true; } return false; }
The above is the detailed content of How to prevent repeated form submission in yii2. For more information, please follow other related articles on the PHP Chinese website!