Sessions
Sessions allow us to get access to data across various pages for each user request. A file is created in a temporary directory on the server by session to store all session variables. This stored data is available to all the pages of a web site during the visit of a particular user.
In PHP, session is accessed through the $_SESSION global variable.
When a session starts,
- A unique ID is generated for that particular session.
- A cookie is sent to the client side.
- All these session variables are saved in the temporary folder on the server.
- When a value is retrived from the session variable, it automatically gets unique session ID from the cookie. Then it looks into its temporary folder for the particular file.
Sessions Opening and Closing
Let's see an example of opening and closing a session.
Step 1 Go to the SiteController.php file. Add the action actionCheckStatus.
- public function actionCheckStatus()
- {
- $session = Yii::$app->session;
-
- $session->open();
-
- if ($session->isActive) echo "Session is Active";
-
- $session->close();
-
- $session->destroy();
- }
Look at the above code, it shows session opening, session closing, checks whether session is active or not and destroys the session.
Step 2 Run it on the browser with the URL,
http://localhost/sess/frontend/web/index.php?r=site/check-status
Accessing Session Data
During accessing of the data, if no session is running than session will automatically start it.
To access the data stored in the session, run the following code.
- $session = Yii::$app->session;
-
-
- $language = $session->get('language');
- $language = $session['language'];
- $language = isset($_SESSION['language']) ? $_SESSION['language'] : null;
-
-
- $session->set('language', 'en-US');
- $session['language'] = 'en-US';
- $_SESSION['language'] = 'en-US';
-
-
- $session->remove('language');
- unset($session['language']);
- unset($_SESSION['language']);
-
-
- if ($session->has('language')) ...
- if (isset($session['language'])) ...
- if (isset($_SESSION['language'])) ...
-
-
- foreach ($session as $name => $value) ...
- foreach ($_SESSION as $name => $value) ...
Flash Data
Flash data is a kind of session data, which possesses the following features.
- Set in one request.
- Only available during the next request.
- Automatically deleted afterwards.
It is mainly used to deliver messages to the end users that is delivered only once such as confirmation messages sent after the login.
Example
Step 1 Create an action ationFlashData in the SiteController.php file.
- public function actionFlashData()
- {
- $session = Yii::$app->session;
-
- $session->setFlash('welcome', 'Successfully Logged In!');
- return $this->render('flashdata');
- }
Step 2 Create a view file flashdata.php in the views/site folder.
- <?php
- use yii\bootstrap\Alert;
- echo Alert::widget([
- 'options' => ['class' => 'alert-info'],
- 'body' => Yii::$app->session->getFlash('welcome'),
- ]);
- ?>
Step 3 Run it on the browser with the URL,
- http:
Cookies
A cookie is a small file that server embeds in the user's system which is used to identify a user.
In Yii, each cookie is an object of yii\web\Cookie.
The yii\web\Request (Collection of submitted cookies in a request) and yii\web\Response (Collection of cookies that need to be sent to a user) maintains the collection of cookies via the property named cookies.
Controller deals with the cookies request and response in an application. Hence, cookies should be read and sent in controller.
Setting Cookies
Send cookies to the end users using the following codes.
-
- $cookies = Yii::$app->response->cookies;
-
-
- $cookies->add(new \yii\web\Cookie([
- 'name' => 'name',
- 'value' => 'sssit',
- ]));
Getting Cookies
To get a cookie use the following code.
-
- $cookies = Yii::$app->request->cookies;
-
-
- $name = $cookies->getValue('name', 'default');
-
-
- if (($cookie = $cookies->get('name')) !== null) {
- $name = $cookie->value;
- }
-
-
- if (isset($cookies['name'])) {
- $name = $cookies['name']->value;
- }
-
-
- if ($cookies->has('name')) ...
- if (isset($cookies['name'])) ...
Removing Cookies
To remove a cookie, use remove() function of Yii.
- $cookies = Yii::$app->response->cookies;
-
- $cookies->remove('name');
-
- unset($cookies['name']);
Example:
Let's see an example to set and show cookie's value.
Step 1 Add the two actions actionSetCookie and actionShowCookie in the SiteController.php file.
- class SiteController extends Controller
- {
-
-
-
- public function behaviors()
- {
- return [
- 'access' => [
- 'class' => AccessControl::className(),
- 'only' => ['logout', 'signup'],
- 'rules' => [
- [
- 'actions' => ['signup'],
- 'allow' => true,
- 'roles' => ['?'],
- ],
- [
- 'actions' => ['logout', 'set-cookie', 'show-cookie'],
- 'allow' => true,
- 'roles' => ['@'],
- ],
- ],
- ],
- 'verbs' => [
- 'class' => VerbFilter::className(),
- 'actions' => [
- 'logout' => ['post'],
- ],
- ],
- ];
- }
-
-
-
-
- public function actions()
- {
- return [
- 'error' => [
- 'class' => 'yii\web\ErrorAction',
- ],
- 'captcha' => [
- 'class' => 'yii\captcha\CaptchaAction',
- 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
- ],
- ];
- }
-
- public function actionSetCookie()
- {
- $cookies = Yii::$app->response->cookies;
- $cookies->add(new \yii\web\Cookie
- ([
- 'name' => 'test',
- 'value' => 'SSSIT Pvt. Ltd.'
- ]));
- }
-
- public function actionShowCookie()
- {
- if(Yii::$app->getRequest()->getCookies()->has('test'))
- {
- print_r(Yii::$app->getRequest()->getCookies()->getValue('test'));
- }
- }
Step 2 Run it on the browser to set the cookie first with following URL,
http://localhost/cook/frontend/web/index.php?r=site/set-cookie
Step 3 Run it on the browser to show the cookie with following URL,
http://localhost/cook/frontend/web/index.php?r=site/show-cookie
No comments:
Post a Comment