Yii Framework handling cookies

Hello,

In the past we have used setcookie() function and $_COOKIE global array to create and access cookies for our domain that expires in N number of days.

If you are using Yii framework, it comes with couple of handy classes that you can manage your cookies utilizing Yii poweress.

These two classes are called

  1. CCookieCollection
    Doc URL: http://www.yiiframework.com/doc/api/1.1/CCookieCollection 
  2. CHttpCookie
    Doc URL: http://www.yiiframework.com/doc/api/1.1/CHttpCookie

CHttpCookie is responsible for creating a cookie. An instance stores a single cookie that includes

  • cookie name
  • cookie value
  • domain it is valid for
  • path
  • expiry date
  • indication if cookie is on secure channel

CCookieCollection is a collection of cookies

Generally you will get all the cookies set by you as

  1. $cookies = Yii::app()->request->getCookies();

where Yii::app()->request is an instance of CHttpRequest

Ok so lets create a cookie

A simple cookie can be created as

  1. $cookie = new CHttpCookie('my_cookie',
  2.                           'my_cookie_value',
  3.                           array('expire'=>(time()+(365*86400)),
  4. 'path'=>'/'));

as per the documentation the default constructor for CHttpCookie is shown below

  1. public void __construct(string $name,
  2. string $value,
  3. array $options=array ( ))

 

Where options can be domain, expire, path, httpOnly, secure

In our example above we are setting our cookie to expire after 365 days

and to send this newly created cookie to our cookie collection we will do the following

Send cookie to cookie collection

  1. $cookies = Yii::app()->request->getCookies();
  2. $cookies['my_cookie']= $cookie;
  3. // where $cookie is what we created earlier

How do we read cookie value

You can use the code below to read your cookie value.

  1. $value=$cookies['my_cookie']->value;

Now $value will have value ‘my_cookie_value

How to remove a cookie

Its really as simple as this. The code below will remove the cookie altogether.

  1. unset($cookies['my_cookie']);

There are a few handy methods in CCookieCollection such as add(), remove() etc that you can use to add or remove cookies if you prefer to use class functions.

Idea of this post was to show how we can set cookies with Yii framework. Yii Framework classes are just a wrapper to already existing functions in code PHP with a little bit of flexibility and event handling added that gives you more control.

I hope that this post maybe useful to you.

Cheers

Advertisement

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Comments

  1. Jessica Thompson says:

    Very much informative.

    Jessica Thompson

Speak Your Mind

*

CommentLuv badge