Using Sessions with the Yii Framework

May 3, 2011
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:

unset(Yii::app()->session['var']);

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.