Yii use arrays in cookies - A helper class for using arrays in cookies

Hi,

This tutorial shows about the CRUD of cookies even for arrays.

This is the helper class for using arrays in cookies

<?php

class CookiesHelper extends CApplicationComponent {

    public function putCMsg($name, $value) {
        if (is_array($value))
            Yii::app()->request->cookies[$name] = new CHttpCookie($name, json_encode($value));
        if (is_string($value))
            Yii::app()->request->cookies[$name] = new CHttpCookie($name, $value);

        return true;
    }

    public function getCMsg($name) {
        if (!empty(Yii::app()->request->cookies[$name])) {
            $return = json_decode(Yii::app()->request->cookies[$name]);
            if (json_last_error() == JSON_ERROR_NONE && !is_string($return))
                return $return;
            else
                return Yii::app()->request->cookies[$name]->value;
        }else
            return 'Cookie not found';
    }

    public function updateCMsg($name, $value) {
        if (!empty(Yii::app()->request->cookies[$name])) {
            $return = json_decode(Yii::app()->request->cookies[$name]);
            if (json_last_error() == JSON_ERROR_NONE && !is_string($return)) {
                array_push($return, $value);
                Yii::app()->request->cookies[$name] = new CHttpCookie($name, json_encode($return));
                return true;
            } else {
                Yii::app()->request->cookies[$name] = new CHttpCookie($name, $value);
                return true;
            }
        }else
            return 'Cookie not found';
    }

    public function delCMsg($name = NULL) {
        unset(Yii::app()->request->cookies[$name]);
        return true;
    }

}

?>

Installation Steps :

  • Create a new php file namely CookiesHelper.php under components folder and copy the above class into the file.
  • Add a array in config/main.php file as follows
'Cookies' => array('class' => 'application.components.CookiesHelper'),

Now you are done!.

You can access the class as follows.

Setting the cookie The function putCMsg has two arguments one is name of the cooke and the other is mixed value either in array or string.

Yii::app()->Cookies->putCMsg('cookie_name1',array('myCookieVal1','val2')); 

Getting the cookie

Yii::app()->Cookies->getCMsg('cookie_name1');

Updating the cookie

Yii::app()->Cookies->updateCMsg('cookie_name1','orange');

Note: If the existing cookie is in array form then it will be pushed to the existing array.

Deleting the cookie

Yii::app()->Cookies->delCMsg('cookie_name1');

If you like don't forget to press +