Home > PHP Framework > YII > How to prevent repeated form submission in yii2

How to prevent repeated form submission in yii2

(*-*)浩
Release: 2019-12-30 10:22:06
Original
2992 people have browsed it

How to prevent repeated form submission in yii2

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
	]
]
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template