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
- CCookieCollection
Doc URL: http://www.yiiframework.com/doc/api/1.1/CCookieCollection - 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
$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
$cookie = new CHttpCookie('my_cookie', 'my_cookie_value', 'path'=>'/'));
as per the documentation the default constructor for CHttpCookie is shown below
public void __construct(string $name, string $value,
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
$cookies = Yii::app()->request->getCookies(); $cookies['my_cookie']= $cookie; // where $cookie is what we created earlier
How do we read cookie value
You can use the code below to read your cookie value.
$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.
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





JC WordPress Coupon Revealer Plugin Pro License
Australian Street Names with City, State and Display Names only, Single Server License
Very much informative.
Jessica Thompson