Using Sessions with the Yii Framework

May 3, 2011 — 90 Comments
The Yii Book If you like my writing on the Yii framework, you'll love "The Yii Book"!

I haven’t written much about the Yii framework lately, mostly because I’ve been working night and day on the fourth edition of my “PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide” book, due out late summer 2011. So I figured I’d put together another little blurb on the Yii framework (by regularly putting out posts on Yii, it’ll be that much easier when I go to write a book on Yii later this summer). In this post, I’m going to talk about using sessions Yii-based sites (in a separate post, I’ll discuss cookies). While not at all hard, the topic, like quite a few things, is not obvious in Yii, or well documented.

The first thing to know about using sessions in Yii is that you don’t have to do anything to enable them, which is to say you don’t have to invoke session_start(), as you would in a standard PHP script. This is the behavior with Yii’s autoStart session property set to true, which is the default. Even without using session_start(), you could, of course, make use of the $_SESSION superglobal array, as you would in a standard PHP script, but it’s best when using frameworks to make total use of the framework. The Yii equivalent to $_SESSION is Yii::app()->session:

Yii::app()->session['var'] = 'value';
echo Yii::app()->session['var']; // Prints "value"

And that’s all there is to it. To remove a session variable, apply unset(), as you would to any other variable:


So…nothing really unexpected there, once you know where to find the session data. The more complex consideration is how to configure sessions for your Yii application. You can do so using the primary configuration file (protected/config/main.php). Within that, you would add a “session” element to the “components” array, wherein you customize how the sessions behave. The key attributes are:

  • autoStart, which defaults to true (i.e., always start sessions)
  • cookieMode, with acceptable values of none, allow, and only, equating to: don’t use cookies, use cookies if possible, and only use cookies; defaults to allow
  • cookieParams, for adjusting the session cookie’s arguments, such as its lifetime, path, domain, and HTTPS-only
  • gCProbability, for setting the probability of garbage collection being performance, with a default of 1, as in a 1% chance
  • savePath, for setting the directory on the server used as the session directory, with a default of /tmp
  • sessionName, for setting the session’s, um, name, which defaults to PHPSESSID
  • timeout, for setting after how many seconds a session is considered idle, which defaults to 1440

For all of these, the default values are the same as those that PHP sessions commonly run using, except for autoStart.

If your site will not be using sessions at all, you would want to disable them by adding this code to the “components” section of protected/config/main.php:

'session' => array (
    'autoStart' => false,

If you are using sessions, for security purposes, you may want to change the session’s name, always require cookies, and change the save path:

'session' => array (
    'sessionName' => 'Site Access',
    'cookieMode' => 'only',
    'savePath' => '/path/to/new/directory',

The save path, in case you’re not familiar with it, is where the session data is stored on the server. By default, this is a temporary directory, globally readable and writable. Every site running on the sever, if there are many (and shared hosting plans can have dozens on a single server), share this same directory. This means that any site on the server can read any other site’s stored session data. For this reason, changing the save path to a directory within your own site can be a security improvement. Alternatively, you can store the session data in a database. To do that, add this code to the “components” section of protected/config/main.php:

'session' => array (
    'class' => 'system.web.CDbHttpSession',
    'connectionID' => 'db',
    'sessionTableName' => 'actual_table_name',

If you choose this route, Yii will automatically create the table if it does not exist. You can also perform any of the other session configuration changes in that code block, too.

So…what else? Frequently, for debugging purposes, and sometimes to store it in the database, I like to know the user’s current session ID. That value can be found in Yii::app()->session->sessionID.

Finally, when the user logs out, you may want to formally eradicate the session. To do so, call Yii::app()->session->clear() to remove all of the session variables. Then call Yii::app()->session->destroy() to get rid of the actual data stored on the server.

And that’s what there is to know about using sessions with Yii, at least that’s all the key information. I hope this helps you with your Yii-based applications. As always, thanks for reading and let me know if you have any comments or questions.

If you enjoyed this post, then please consider following me using your favorite social media, the RSS feed, and/or by subscribing to my newsletter. Or go crazy, and buy one or more of my books . Thanks!

90 responses to Using Sessions with the Yii Framework

  1. a very good post,thx.

  2. “when I go to write a book on Yii later this summer”, I like how you just hide that bit in there haha. I’ll be waiting for that book! I’m looking for a good framework to build a CMS from codeigniter is on the cards too

  3. Thank you so much for mentioning the session save path! I had been pulling out my hair trying to figure out why my one Yii app was losing sessions, and when I read that line I checked the user rights on that folder and sure enough, the user running the Yii vhost didn’t have rights. Problem solved!

    Thanks as always for your great articles.

    • You’re quite welcome. Thanks for the feedback. Your company (Spark Genius) does good work, by the way. I’m thinking of your company’s site and the Fresh Reminders site, in particular. I’m adding you to my list of potential designers to hire on future projects!

  4. Thax,very useful post

  5. I was pulling my hair out, dealing with sessions and I didn’t take time “to google” a little bit about this stuff. It was a great relief to my stress to have found this article. It was really useful.
    Thanks a lot !!

  6. Larry, thank you so much for all these posts on Yii! I struggled almost 1 month with the Agile Dev. Book on it and still couldn’t do anything. Then I stumbled upon your posts and within 2 days I felt like at home. Already after the first series I fell in love with Yii and with your clear way of explaining everything.
    How is it going with the book on Yii? Please work on it as hard as possible.. YOU will be the one that will really bring Yii to the masses and make it the most beloved PHP framework out there.

    • Hello, Adrian. Thanks for the nice words. I’ve not seen the Agile book, but I’ve heard similar comments. Currently, the work on the Yii book isn’t happening, as I’m writing a JavaScript book. But I’m hoping to get to it at the end of this year. We’ll see. If you subscribe to my newsletter, you’ll get updates on its progress. Thanks for your interest!

  7. Thanks a lot for this (and other tutorials).There seems to be a bug with the framework. If the session name has a space in it (like in the example above) then the login will start failing silently.

    • Thanks for the nice words and for posting about the space in the name issue. I’ve not witnessed that myself, however, even when using PHP to handle the sessions directly, I wouldn’t have ever thought to put a space in the name, so this may not be a Yii issue but a PHP issue (I’m not sure; just guessing).

  8. thanks larry, It was great as usual 😉

  9. Thank you!

  10. I wrote in protected\main.php :
    ‘session’ => array (
    ‘autoStart’ => false,
    ( I copied from this article :-) )

    and I received


    Property “CWebApplication.session” is read only.


    Why can I disble session?

    Miguel Trejo

  11. Hey Larry,
    Thanks a ton for your Yii tutorials. It really translates Geek into English :)
    I had one question, What are the repercussions of saving session data on Servers or database in Yii’s on performance?


    • Thanks, Mohit. You’d have to do benchmarks to confirm for your specific situation, but I think that saving session data in a database has a negative impact on performance (Yii or not), but it has other benefits. It just depends what is most important.

  12. I want to know how to get user_id in session table?

  13. I seriously don’t think that the savePath on a well configured server system should be ever touched. I think that giving the advice that this somehow may heighten the security level is misleading.
    On the contrary, moving the session save path to a user-own directory, in extreme case maybe a web directory, will worsen the sitation by far. I can tell because in our open source software we offered this option for a short time and it led to teh said situations until we removed the setting again to protect users from playing with it.
    If you need to play with that setting then something is off with your server in general.

    Otherwise a fine article, thanks.

    • Thanks for your input. On a “well configured” server, changing the savePath is probably not necessary. But on most servers with most hosts, it is completely necessary, in my opinion. You would never want to make the sessions directory a public Web directory, of course. And even on a “well configured” server, properly changing the savePath will never be a problem.

  14. Lovely post larry,
    you rock! i’ve started porting a project of mine to Yii. i hope you’ll indulge me when i come with questions.

    • Thanks for the nice words and good luck with your project. I’m more than willing to answer questions, but please use the support forums for posting them.

  15. Thanks a lot for this great article. I also have one questions.
    Article says “cookieMode, with acceptable values of none, allow, and only, equating to: don’t use cookies, use cookies if possible, and only use cookies; defaults to allow”
    Does this setting control the saving of session id or session data in a cookie?
    For example if I set cookieMode to only will the yii application save session data or just the session id in a cookie?

  16. Is there any way to have sessions turned off for portions of the site and turned on for other parts? Say for example an admin section uses sessions and the rest of the site does not?

    Been trying to find an answer on that one.

  17. Thank you for the well written and insightful article.

    Can you elaborate on whether one should choose cookie-based or session-based approach for storing user identity and related data? Or should one use both?

    Can session-based approach become a performance problem? Is cookie-approach secure enough?

    • Thanks for the nice words. As for your question, I would not use both cookies or sessions, as you end up with the negatives of both that way. I use sessions when security is more of an issue or you need to store more data. I use cookies when less data needs to be stored or the data needs to be stored for longer time periods. I couldn’t speak to the performance concerns in detail except that cookies require the data to be sent back and forth with each request, which can impact the network performance.

  18. Hi,
    there is a problem ,
    usually in PHP I can use array in $_SESSION, Like
    $_SESSION[‘X’][‘Y’] = ‘zz';
    I can’t use:
    Yii::app()->session[‘X’][‘Y’] = ‘value';


    Carmelo Carchedi
    Juniorbi Sas

  19. Thanks for sharing your wisdom with us. How do sessions that have expired get deleted from the sessions table? I saw that there is an expired field, but what process does the actual culling if Yii::app()->session->clear() and Yii::app()->session->destroy() are not called?

  20. Hai Larry.
    You are doing awesome with this yii framework tutorials thanks very much .Especially the rookies like us
    How we can maintain session through out all pages . I mean all pages should be accessed only by logged in users

  21. Just a question on session ID when its required externally, for example an eCommerce application making a request and receiving a response from a payment gateway where the session ID is required to maintain state for the transaction.

    How is this done? I am accustomed to simply appending session ID as a $_GET parameter in the URLs. Is this how it can be done in Yii also?

    In regard to comment from Carmelo Carchedi – I’ve actually used a multidimensional object (shopping cart) in Yii session without any issue whatsoever. I instantiate my shopping cart class and then assign is to session to maintain its state.

  22. Thnks Lorry , Really it’s very useful to me, but the thing is i am new to yii, sorry for asking this, where i need to write this statement

    ,pls suggest me

    • You’d put that in a controller, most likely, if you’re setting a session value and put it in a controller or a view if you’re retrieving it, depending upon what you’re doing with the retrieved value.

  23. Hi Guys,

    I think mentioning sessionName is still required if you are storing the session data in a database and wants to share session among multiple applications.


  24. Very nice explaination.

  25. I’m new to Yii and your post so clearly, easy to understand. Thank you very much!

  26. thank you

  27. nice…it is very useful to me……thanks…………
    But i am using $_SESSION[‘store_id’] values session timeout automatically having undefined index:store_id..
    i tried but i cant find solution pls help me…..

    • in the config file set session object as follows:
      ‘session’ => array (
      ‘autoStart’ => false,

      Please let me know if further help required

  28. How can i do a redirect when the session expires to my login page?

  29. Sir in case of database stored sessions, will it will be automatically delete when we close the browser…

  30. But i am using $_SESSION[‘store_id’] values session timeout automatically having undefined index:store_id..
    i tried but i cant find solution pls help me…..

  31. nice…it is very useful to me……thanks…………

  32. Awesome post :D. This saves me a lot of time managing session timeout implementation.

  33. Hi there,
    first of all let me say that yours are awesome posts and really helpful, thanks!
    second, and about sessions (I think) I am a little bit desesperate with one app I did using Yii on a load balancer server (AWS). Can’t make people log in, the app runs perfect on local and DEV (single server) but breaks on load Balancer. My users are on my Database {{User}} and my sessions stored on DB, but it still doesn’t let my users in. :( Any…light?
    thanks anyway and congrats again for your job.

    • I have a similar problem. I have my application distributed from some servers in AWS EC2 and my database is on a RDS service in AWS cloud. so, I don’t knows how I can know if an user are log in yet and if that user is admin or other kind of user with the CDbHttpSession. I suppose that I have to had a login system in every my distributed applications but how can I compare that sessions with this?

    • Make sure, you have specified ‘autoStart’ => false, in main.php

  34. How to set session timeout in yii framework

    • Set session timeout property in config.php as follows :
      ‘session’ => array (
      ‘autoStart’ => false,
      ‘timeout’ => 1200, //timeout after 20 mins
      //set other properties of Session component below this line

  35. thanks Larryullman

  36. Amazing thanks…
    Bro how to display data from database on index match session idProduk? please help

  37. Hi Larry,
    That was a great post. I would like to know how can i read the BLOB object stored in the database.
    Thanks in advance.


  38. I am using session in modules:
    Yii::app()->session[‘chapter_search’][‘subject_id’]= $subject_id;
    and not getting value in echo Yii::app()->session[‘chapter_search’][‘subject_id’];

  39. As always great post. Your posts have helped me a lot in learning Yii.

    PS: Have you written an article about using CUserIdentity with session?

  40. A M B Nishanth March 26, 2014 at 2:51 pm

    Resource of Yes It Is

  41. A M B Nishanth March 26, 2014 at 2:55 pm

    A validation is done using SESSION values in my work but I am not able to find that from where the values come. Please suggest me solve this problem

  42. can we used different database for session?

  43. Abhishek Agrawal May 17, 2014 at 4:23 am

    HI larry

    I have configured session for my application in yii to destroy session data after 1 min but it could not happen so. I have done the configuration under the components section of main.php like this –

    ‘session’ => array(
    ‘autoStart’ => true,
    ‘timeout’ => 60, // 1 minutes,
    ‘savePath’ => ‘session_data/’,
    Please guide me where m missing something..

    Thanks in advance

  44. Where I create folder ? in protected folder or in my base Apps ??

  45. How can write the session method for more than 1 controller?

  46. thank u but i have one doubt (how to login in same form and get values in different tables with session?)
    please help me sir!!

  47. Thanks helped for me. Was wondering how to auto start session using Yii.

  48. Very Good post about that security thing where any site can use session data of other site if session directory is same..Thanks

  49. Oliver Hernández May 3, 2015 at 5:06 pm

    Thanks for the input.

    I need destrur the session by closing the browser.
    you have any idea how to do it?

Trackbacks and Pingbacks:

  1. What is Larry Thinking? #42 => Doing What I Do, Part 3 – Larry Ullman - July 29, 2011

    […] Yii framework, I’ve recently written two postings on managing state using the framework. The first is on sessions; the second on cookies. Neither is particularly difficult to do using Yii, once you know the right […]

  2. 在Yii中使用Session » 非你不可 - September 16, 2011

    […] […]

  3. (转)Yii Framework中关于Session的笔记 | uguke个人blog - March 12, 2012

    […] 感觉这篇文章是从这里翻译过来的,至少内容上是。 本作品采用知识共享署名-相同方式共享 3.0 […]

  4. Yii Project Relocation Problem | Playing with technology - March 10, 2014

    […] do not have access to the temporary directory on FatCow (downside of a good deal). I read a post by Larry Ullman discussing Yii’s implementation of sessions where he pointed out that you can specify the directory to store session data or set up a database […]

Comments are great, but I'd strongly prefer any requests for assistance get made in the support forums. Thanks!