Yii session
Yii session : Session is used to store data which persists across the multiple pages. Yii provides session management in object oriented style. Here in this tutorial we are going to explain how you can create session and get it across the request.
Yii session
Yii set session variable
You can set session variable in yii as below –
Yii session: Set Session Variable Example
$app = app(); $session = Yii::$app->session; $session->set('userId', 124322); //or $session['userId'] = 124322; |
In the above example we have created a session variable userId which stores the value 124322. Session variable can be set either using the $session[‘userId’] variable or $session->set(‘userId’, 124322); both will set the session variable with the given value.
Yii get session variable
You can get session variable in yii as below –
Yii session: Get Session Variable Example
$app = app(); $session = Yii::$app->session; $userId = $session->get('userId'); //or $userId = $session['userId']; echo $userId; // it will give the 124322 |
If you want to access the session variable value in yii you can use the syntax as above which will give you the session value.
Yii clear session : Remove | Unset Session variable
You can clear session variable in yii as below –
Yii clear session: destroy session Example
$app = app(); $session = Yii::$app->session; $session->remove('userId'); |
If you want to unset the session variable value in yii you can use the syntax as above which will remove the session variable.
More About Yii Session
Let Us have some more example on yii session-
Yii Session Flash Data
Flash data is a special kind of session variable which is set for one request and destroyed for other request automatically.
Yii Session Set Flash Data: Example
$app = app(); $session = Yii::$app->session; $session->setFlash('successMessgae', 'Data updated successfully.'); |
This becomes important when you are dealing with the messages which needs to be displayed only once example – You want to show the success message when data is updated and destroy the message after this. The above example contains the same example.
Yii Session Get Flash Data: Example
Yii Session Get Flash Data: Example
$app = app(); $session = Yii::$app->session; echo $session->getFlash('successMessgae'); // will print - "Data updated successfully." |
The above example will show the flash message stored in the variable successMessage. If you print the above example it will give you – Data updated successfully.
Advertisements