Home > Article > Backend Development > How to solve Yii2 prevention rules and restrictions for visitors and users
This article mainly introduces Yii2’s solutions to tourists and user prevention rules and restrictions. It briefly analyzes the principles and corresponding setting methods of Yii2’s tourists and user prevention rules and restrictions. Friends in need can refer to the following
This article analyzes Yii2’s solutions to visitor and user prevention rules and restrictions with examples. I would like to share it with you for your reference. The details are as follows:
I am currently working on a project using Yii2.0, and I need to implement a function: some pages cannot be accessed without logging in, that is, visitor status access restrictions. After checking the information for a long time, I finally found the answer. The solution is as follows:
In access, access means access, and there is a configuration item:
'only'=>['login','about']
What does this mean? , which means that it only works within the two actions of login and about, that is, when the action is login or about, it will enter the rules for the next step of verification.
But what if we want to deny access to other actions except login and registration? There are other configurations. We change only to except. What does it mean? It means to exclude something, that is, it works for actions other than login and signup. Next, in:
rules=>[['action'=>['login','signup'],'allow'=>true,'roles'=>['?']]]
, rules are rules. You can write multiple ones here. actions refers to which action the rules are for. allow refers to whether access is allowed. The 'roles' field is key. This is Roles allowed access. in? Represents the visitor, @ represents the logged in user .
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'except' =>['login','signup'], 'rules' => [ [ 'actions' => ['login','signup'], 'allow' => true, 'roles' => ['?'], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'logout' => ['post'], ], ], ]; }
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website !
Related recommendations:
How to deal with the escape of routing links in Yii2.0 Basic code
About combining in yii2 Code for gridview using modal pop-up window
How to create simple widgets using yii2.0
The above is the detailed content of How to solve Yii2 prevention rules and restrictions for visitors and users. For more information, please follow other related articles on the PHP Chinese website!