How to bend CakePHP's session handling to your needs

by ADmad
This article is an attempt to break the myth that Cakephp's current session handling is not easily customizable.
There are various tickets on stating that current session handling by CakePHP is not configurable enough and asking for enhancements to it. Here are a few examples.

It seems most people don't release that you can specify your own config file using which you can set session handling as per your needs and don't have to resort to hacking core files. If you check your app/config/core.php there is a comment which states:
To define a custom session handler, save it at /app/config/(name).php.
Set the value of '' to (name) to utilize it in CakePHP.
So we are going to do just that.

In your core.php put Configure::write('', 'my_session_handler');
Then make a file app/config/my_session_handler.php and put your stuff there. Here's an example file

// You can copy the ini_set statements from the switch block here
// for case 'php' (around line 484) and modify to your needs.

// Lets assume our config value for Security.level is 'medium'

//Get rid of the referrer check even when Security.level is medium
// or you can use this to restore to previous value
// ini_restore('session.referer_check');

//Cookie lifetime set to 0, so session is destroyed when browser is closed and doesn't persist for days as it does by default when Security.level is 'low' or 'medium'

//Now this feels a bit hacky so it would surely be nice to have a config variable for cookie path instead.
//Cookie path is now '/' even if your app is within a sub directory on the domain
$this->path '/';

//This sets the cookie domain to "" thereby making session persists across all sub-domains

//Comment out/remove this line if you want to keep using the default session cookie name 'PHPSESSID'
//Useful when you want to share session vars with another non-cake app.

//Makes sure PHPSESSID doesn't tag along in all your urls

So this example file above shows how you can customize session handling, at least for php based session handling. I personally haven't used database based session handling so not sure how things would work out it that case but i don't think it would be much of a problem either. Please feel to point out any mistakes on my part.


More on Tutorials



  • ptucky posted on 06/30/11 04:32:06 AM
    Try to set this ini_set('session.cookie_lifetime', 0);
    It work on IE and SaFari but not working on Firefox. Any Idea.
    Thanks in advance
  • stevecomrie posted on 03/22/11 04:07:52 PM
    Thanks for this. Saved me a couple hours of hair-pulling I'm sure.

    I was having trouble specifically with session.cookie_path and

    Code was previously working on my local machine, but something must have been different about the production server. The changes I'd made in core.php to were holding, but cookie_path was being clobbered because I had the cake app running in a sub-folder.
login to post a comment.