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