Yii 1.1: Cookie management in Yii


Cookie management in Yii is easy, but may not be so obvious for the beginners to this framework, so I wrote this simple article to clear some doubts out.

Cookie management

Reading a cookie

To read a cookie value, use following code:

$cookie = Yii::app()->request->cookies['cookie_name']->value;

Since Yii 1.1.11 you can also access the cookie value directly without accessing the value property first.

$value = (string)Yii::app()->request->cookies['cookie_name'];

Note: You should only use this if you are sure the cookie exists. Also this may not work on PHP prior to 5.2 (See PHP.net -> __toString()).

See also "Safe reading" in the next chapter.

Writing a cookie

Notice, that you have to specify the name twice, if you want to use this:

Yii::app()->request->cookies['cookie_name'] = new CHttpCookie('cookie_name', $value);

See also "Reload required" in the next chapter.

Configure a cookie

Starting with Yii 1.1.11 you can configure an cookie upon creation.

$cookieCollection['name'] = new CHttpCookie('name', 'value', $options);

The option parameter is internally passed to the public method CHttpCookie::configure() which accepts an array with the following keys:

Deleting a cookie

To delete a cookie, use following code:


or you can delete ALL cookies with:


Notice, that cookie will not be deleted until next page reload - see "Reload required" and "Cookie expiration problem" in the next chapter.

What to remember about?

Cookies are objects

Cookies in Yii are read from CHttpCookie which is an object. Also it is important to know that


is an instance of CCookieCollection which extends CMap, therefore it is possible to use simliar to an array.

Safe reading

On the same basis, as above, if a particular cookie does not exists, a corresponding object (CHttpCookie instance) for it will not be created! Trying to read such cookie will result in error "Trying to get property of non-object". To avoid that, it is always better to read a cookie using ternary operator, like that:

$value = isset(Yii::app()->request->cookies['cookie_name']) ? Yii::app()->request->cookies['cookie_name']->value : '';
// or
$value = Yii::app()->request->cookies->contains('cookie_name') ?
Yii::app()->request->cookies['cookie_name']->value : '';

This way, you'll get either cookie value or an empty string.

This example also gives us idea how to check, if particular cookie exits:

$is_cookie = !isset(Yii::app()->request->cookies['cookie_name']);

Reload required

Please, remember that server has actually nothing to do with the cookies. It only inform browser (in request result) about changes to cookies. Browser is responsible to do the job.

Therefore, cookies changes are NOT visible until next reload of page (next request). If you set a cookie value in some place in your code and try to read if few lines below, you'll get empty value or warning (or error in strict PHP mode).

This, of course, goes also to modifying cookie value or deleting them, which also requires reload of a page to succeed. Common pitfall, when developing shopping-cart-like solutions is to delete a cookie and testing if it exists in the same page. This will not work - cookie will not be deleted until next reload.

Cookie expiration problem

If you set cookie like in above examples, it will be deleted automatically upon closing a browser (or clearing all cookies with proper option). Again - this is browser, not server job. You must close all open windows (copies) of browsers, because only then all cookies will be deleted. In some rare situation (browser hang-up) you can have a hidden copy (window) of a browser still in memory (on processes list) of which you may not be aware. Starting up new copy of browser will then show you all cookies that were meant to be deleted, as existing and having value - that is because that hidden window prevented browser from fully closing itself, and only then deletion of cookies is a fact.

To set a cookie that will not be deleted upon browser closure (like the one in default Yii login screen, where cookie is available for thirty days after last login), you must set it's expiration date. Like that:

$cookie = new CHttpCookie('cookie_name', $value);
$cookie->expire = time()+60*60*24*180; 
Yii::app()->request->cookies['cookie_name'] = $cookie;

As, you can see - we're setting cookie expiration time relative to current time (first common pitfall) and as a timestamp, not date-time variable (second common pitfall). That is, why in above example we used time() PHP function.

We're counting expiration time in seconds (third common pitfall), so in above example we set cookie expiration date to be 180 days from this moment, which equal to 15 552 000 seconds, but it is of course easier to write it as equation.

Common settings for cookie expiration time:

  • an hour: 3600 seconds,
  • an day: 86400 seconds,
  • a week: 604800 seconds,
  • a month (unified = 30 days): 2592000 seconds,
  • a year (unified = 12 months of 30 days): 31104000 seconds.

Cookies in JavaScript

By default, you can access your cookies from both PHP code (examples above) and JS code incorporated into your pages. Since JS script handling is entirely done in browser, problems with need of reloading page are not related here.


CHttpCookie.httpOnly property decides, whether particular cookie is available to both PHP and scripting languages. This is default setting (false). By setting it to true, you will rise your application security (this reduces identity theft through XSS attacks), but your cookies will not be available to JS code.


If you're using any widget or other class that is forcing Yii to publish jQuery code, you can make use of jQuery Cookie Plugin (jquery.cookie.js file), that ships with jQuery on-board Yii. Managing cookies this way in JavaScript is extremely easy. For example, to set a cookie, you call:

$.cookie('the_cookie', 'the_value');

To read it - use standard jQuery approach of:

var cookie = $.cookie('the_cookie');

And to delete cookie, simple set its value to NULL

$.cookie('the_cookie', null);

Look for jquery.cookie.js file published in your assets folder and read its head comment for more examples of using cookies with this jQuery plugin.

Non-jQuery approach

If you don't use jQuery in your application or for other reasons don't want to use jQuery Cookie Plugin, you can use these two functions for accessing cookies in JavaScript:

function readCookie(cookieName)
        var theCookie = '' + document.cookie;
        var ind = theCookie.indexOf(cookieName);
        var ind1 = theCookie.indexOf(';', ind);
        if(ind1 == -1) ind1 = theCookie.length;
        if(ind == -1 || cookieName == '') return '';
        return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
function setCookie(cookieName, cookieValue, nDays)
        var today = new Date();
        var expire = new Date();
        if(nDays == null || nDays == 0) nDays = 1;
        expire.setTime(today.getTime() + 3600000 * 24 * nDays);
        document.cookie = cookieName + '=' + escape(cookieValue) + ';expires=' + expire.toGMTString();

As you can see (second function) - time offset in JavaScript is counted in miliseconds, therefore you must recalculate above mentioned example time periods times 1000.

Further reading

Please, extend this article, if you find any mistakes or that something is missing here.


Russian version

Total 5 comments

#16454 report it
realtebo at 2014/02/25 03:59am
Be aware: do not use dots in cookie name

If you try to save a cookie with a dot ('.') inside the cookie name, it will be automatiaclly converted in a underscore ('_').

#6308 report it
marcovtwout at 2011/12/27 12:18pm
Cookie common pitfalls

Since internally Yii uses php's set_cookie(), take a look at their common pitfalls:

Common Pitfalls:

  • Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
  • Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.
  • Because setting a cookie with a value of FALSE will try to delete the cookie, you should not use boolean values. Instead, use 0 for FALSE and 1 for TRUE.
  • Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes.
#4640 report it
Equ at 2011/07/28 01:48pm
Delete cookie

Note, that unset(Yii::app()->request->cookies['cookie_name']) (or even unset($_COOKIE['cookie_name']) doesn't always work, because it doesn't delete cookie on client side. At least in my case this was a problem.

A solution to this is to set your cookie expiration time to one hour ago as was suggested in official php manual:

// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".example.com", 1);
#2932 report it
Trejder at 2011/02/26 08:05am
Answer to suggestion on Safe Reading

@junxiong: Hm... I have E_ALL (or even higher - E_STRICT) turned on and was testing this piece of code and had no error on non-existing cookies. Maybe Yii handles this problem and returns empty string in such situation? I'm not sure...

But, after all - thanks! :] - it is always good to be safer, if you can - therefore, your solution won't hurt, if cookie exists and provides better security, if it doesn't. So I fully agree with you.

#2931 report it
junxiong at 2011/02/26 07:05am
Suggestion on Safe Reading

I don't know this is correct or not but, for me safe reading, should be like this:

$cookie = (isset(Yii::app()->request->cookies['cookie_name'])) ? Yii::app()->request->cookies['cookie_name']->value : '';

Because if the E_ALL is turn on, then it's still going to error, if the 'cookie_name' element is not defined.

Leave a comment

Please to leave your comment.

Write new article