Friday 6 January 2017

YII Frame Work Cookies

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.
  1. public function actionCheckStatus()   
  2.    {   
  3.   $session = Yii::$app->session;   
  4.   // open a session   
  5.   $session->open();   
  6.   // check if a session is already active   
  7.   if ($session->isActive) echo "Session is Active";   
  8.   // close a session   
  9.   $session->close();   
  10.   // destroys all data registered to a session   
  11.   $session->destroy();   
  12.    }  
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
YII Session 1

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.
  1. $session = Yii::$app->session;  
  2.   
  3. // get a session variable. The following usages are equivalent:  
  4. $language = $session->get('language');  
  5. $language = $session['language'];  
  6. $language = isset($_SESSION['language']) ? $_SESSION['language'] : null;  
  7.   
  8. // set a session variable. The following usages are equivalent:  
  9. $session->set('language''en-US');  
  10. $session['language'] = 'en-US';  
  11. $_SESSION['language'] = 'en-US';  
  12.   
  13. // remove a session variable. The following usages are equivalent:  
  14. $session->remove('language');  
  15. unset($session['language']);  
  16. unset($_SESSION['language']);  
  17.   
  18. // check if a session variable exists. The following usages are equivalent:  
  19. if ($session->has('language')) ...  
  20. if (isset($session['language'])) ...  
  21. if (isset($_SESSION['language'])) ...  
  22.   
  23. // traverse all session variables. The following usages are equivalent:  
  24. foreach ($session as $name => $value) ...  
  25. 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.
  1. public function actionFlashData()   
  2.    {   
  3.   $session = Yii::$app->session;   
  4.   // set a flash message named as "welcome"   
  5.   $session->setFlash('welcome''Successfully Logged In!');   
  6.   return $this->render('flashdata');   
  7.    }   
Step 2 Create a view file flashdata.php in the views/site folder.
  1. <?php   
  2.    use yii\bootstrap\Alert;   
  3.    echo Alert::widget([   
  4.       'options' => ['class' => 'alert-info'],   
  5.       'body' => Yii::$app->session->getFlash('welcome'),   
  6.    ]);   
  7. ?>  
Step 3 Run it on the browser with the URL,
  1. http://localhost/flash/frontend/web/index.php?r=site/flash-data  


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.
  1. // get the cookie collection (yii\web\CookieCollection) from the "response" component  
  2. $cookies = Yii::$app->response->cookies;  
  3.   
  4. // add a new cookie to the response to be sent  
  5. $cookies->add(new \yii\web\Cookie([  
  6.     'name' => 'name',  
  7.     'value' => 'sssit',  
  8. ]));  

Getting Cookies

To get a cookie use the following code.
  1. // get the cookie collection (yii\web\CookieCollection) from the "request" component  
  2. $cookies = Yii::$app->request->cookies;  
  3.   
  4. // get the cookie value. If the cookie does not exist, return "default" as the default value.  
  5. $name = $cookies->getValue('name''default');  
  6.   
  7. // an alternative way of getting the "name" cookie value  
  8. if (($cookie = $cookies->get('name')) !== null) {  
  9.     $name = $cookie->value;  
  10. }  
  11.   
  12. // you may also use $cookies like an array  
  13. if (isset($cookies['name'])) {  
  14.     $name = $cookies['name']->value;  
  15. }  
  16.   
  17. // check if there is a "name" cookie  
  18. if ($cookies->has('name')) ...  
  19. if (isset($cookies['name'])) ...  

Removing Cookies

To remove a cookie, use remove() function of Yii.
  1. $cookies = Yii::$app->response->cookies;  
  2. // remove a cookie  
  3. $cookies->remove('name');  
  4. // equivalent to the following  
  5. 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.
  1. class SiteController extends Controller   
  2. {   
  3.     /**  
  4.      * @inheritdoc  
  5.      */   
  6.     public function behaviors()   
  7.     {   
  8.         return [   
  9.             'access' => [   
  10.                 'class' => AccessControl::className(),   
  11.                 'only' => ['logout''signup'],   
  12.                 'rules' => [   
  13.                     [   
  14.                         'actions' => ['signup'],   
  15.                         'allow' => true,   
  16.                         'roles' => ['?'],   
  17.                     ],   
  18.                     [   
  19.                         'actions' => ['logout''set-cookie''show-cookie'],   
  20.                         'allow' => true,   
  21.                         'roles' => ['@'],   
  22.                     ],   
  23.                 ],   
  24.             ],   
  25.             'verbs' => [   
  26.                 'class' => VerbFilter::className(),   
  27.                 'actions' => [   
  28.                     'logout' => ['post'],   
  29.                 ],   
  30.             ],   
  31.         ];   
  32.     }   
  33.   
  34.     /**  
  35.      * @inheritdoc  
  36.      */   
  37.     public function actions()   
  38.    {   
  39.         return [   
  40.             'error' => [   
  41.                 'class' => 'yii\web\ErrorAction',   
  42.             ],   
  43.             'captcha' => [   
  44.                 'class' => 'yii\captcha\CaptchaAction',   
  45.                 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,   
  46.             ],   
  47.         ];   
  48.     }   
  49.   
  50.     public function actionSetCookie()   
  51.     {   
  52.         $cookies = Yii::$app->response->cookies;   
  53.         $cookies->add(new \yii\web\Cookie   
  54.             ([   
  55.             'name' => 'test',   
  56.             'value' => 'SSSIT Pvt. Ltd.'   
  57.             ]));   
  58.     }   
  59.   
  60.     public function actionShowCookie()   
  61.     {   
  62.         if(Yii::$app->getRequest()->getCookies()->has('test'))   
  63.         {   
  64.             print_r(Yii::$app->getRequest()->getCookies()->getValue('test'));   
  65.         }   
  66.     }   
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
YII Cookies 1
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