CakePHP is a PHP framework which is turning out to be most useful, and very flexible. I’ve embarked on a few little projects with it, and thought I would spread a little understanding with regards to the session component - as I struggled to find a concise set of examples to help me on my way.
By default, a CakePHP application will automatically create a session instance when you’re browsing through it - this is good, but it’s not that obvious about where to go after this. If you were to put the following code into a controller:
print_r($this -> Session -> read());
The contents of the session variable would be printed out (print_r() dumps the contents of an array to screen). Without any influence over the session data, it would look like this:
Array ( [Config] => Array ( [rand] => 262820453 [time] => 1161876896 [userAgent] => c7f575cbe5a4b7ad0efb748d54124611 ) )
(Bear in mind that the numbers & characters will all be different for you.)
If you are looking to disable this default session behaviour, set the AUTO_SESSION constant to false in /app/config/core.php.
Writing a variable into the session
Anyway, let’s get onto some more interesting subject stuff - making the Session component work for us. If you want to write one value into the session, it’s merely a case of doing:
$this -> Session -> write("variable", "value");
If you look at a dump of the session array (print_r($this -> Session -> read())) you will see that right at the end of the array, there’s the text “[variable] => value” - magic.
Reading a variable from the session
If you want to use this session variable anywhere in your application, you can simply do:
$this -> Session -> read("variable");
This will return the string “value”.
Putting objects into the session
Handily, you can store entire objects in the Session component - useful for passing information backwards and forwards regarding a user account/profile or the contents of a shopping cart. All you need to do is change the “value” part of the above example to be an array instead of a standard string value. For example:
$user_email = $this -> data['User']['email']; $user = $this -> User -> find("email = '$user_email'"); $this -> Session -> write('User', $user['User']);
In the above working example we expect a form to have been submitted to the controller containing a “User/email” value - we then look in the Users database table to find a row with the given e-mail address. After we’ve found it, we store it into the Session component. Please note the $user['User'] is not the entire array as we only want the user information - there may well be other rows returned by CakePHP depending on your model associations (e.g. A Profile could belong to a User, and our database query above would return the Profile data too.)
Considering the above example, how would we get specific data out of the Session component? Easy, but not obvious:
$this -> Session -> read("User.email");
Closing/destroying a session
Most uses of destroying a session will for logging users out of a system - and it’s made very easy. For neatness it’s better to check and make sure the session is still valid before attempting to destroy it:
if ($this -> Session -> valid()) { $this -> Session -> destroy(); $this -> redirect('/'); }
It’s also courteous to redirect the user somewhere useful.
Other stuff
There’s a little more to session handling within CakePHP - it’s worth looking into it. Features such as checking values stored in a session, storing flash() messages in a session, deleting specific values etc etc. Have a gander at the CakePHP API documentation on the Session component to get up to speed. If you’re not so sharp on CakePHP yet, check back to the examples above - they should outline the steps needed to use the other functions.
If anything has been unclear, post a comment and I’ll get back to you - I went through the whole thing with a shade of briskness.

There is a small typo: $this -> Session -> reader(???User.email???); should be $this -> Session -> read(???User.email???);
Whoops - thanks! Corrected in the article.
Thanks Kez, I’m just getting started with CakePHP and your post helped me out. It’s the top Google result for “cakephp sessions”.
$user_email = $this -> $data['User']['email'];
should be:
$user_email = $this -> data['User']['email'];
(no $ sign before data)
Thanks R557 - corrected.
this’s really too good
keep it up
thanks a lot. i found it very useful as a beginner of cake. i want to create a user login/logout. if the user is logged in the status will be a logout link, else a login a link.
can u please help on this..
thanks.
Very effective. Thanx.
Thank you, I couldn’t figure out how to read an array variable directly from the Session, and had to copy it to an empty array to check a value. Maybe I went through the manual too quickly…
thanks,
i’m beginner cake user, i still confuse, why the session->destroy couldn’t destroy the session??
any solutions??
Instead pf print_r(), if you are using CakePHP, try using the Cake global function pr(). It is print_r() plus useful-for-debugging formatting extras. (i.e. a set of tags)
thanks a lot. very good posting. it’s help a lot.now i could understand how session works in CakePHP. again thanks.
Hi… i’ve a problem writing in the session variable.
In a controller i can write a new value then read in the view, but if i change the view (same controller, different function), the session variabe resets and lost de value wroted in the other view (controller function)
This happen in all browsers.. have you any idea?
Hello,
In my project login session id not getting
in another controller.
Unable to get session value.
used below function.
Help Me…
shruti
Thanks, this helped me really out, especially the “Easy, but not obvious:”-Part
Thanks a lot! You wrote the really necessary addition to the info from the manual, which is regrettably very sparse in the session chapter!
Thank you
Anja
Hi,
An excellent article for beginners, i have a problem,if i try to login on two systems, which gives to different set of rows in database table cake_sessions table of cake 1.2.6311.
————————————
‘akqccs9apjl42o59dl64a06f27′, ‘Config|a:4:{s:9:”userAgent”;s:32:”d11fe63c042d4c35cd6522843a66c0a6″;s:4:”time”;i:1207309584;s:4:”rand”;i:14590;s:7:”timeout”;i:9;}Message|a:0:{}User|a:3:{s:2:”id”;s:2:”20″;s:8:”username”;s:7:”ukirfan”;s:9:”logged_in”;s:1:”0″;}’, 1207309584
—————————————–
‘j8o7agtse87sv5c48tgrk559g5′, ‘Config|a:4:{s:9:”userAgent”;s:32:”997b9875f784c0b27d7e52d280be6c4b”;s:4:”time”;i:1207309564;s:4:”rand”;i:1868;s:7:”timeout”;i:9;}User|a:3:{s:2:”id”;s:2:”20″;s:8:”username”;s:7:”ukirfan”;s:9:”logged_in”;s:1:”0″;}Message|a:0:{}’, 1207309564
——————————-
My Question is how do i destroy all clone sessions which have the same username.
$this -> Session -> destroy();
only destroys those session rows on which the system made a request.
Thanks.
Irfan
shruti,
i faced a similar situation where it appeared as though session values were not getting transferred to another controller.
when u access another controller through address bar , the session is regenerated and ur data gets destroyed.
simpler solution is:
try to access other controller, from within html links created in “view” files.
example in view.ctp
—————————-
Controller 1 view files.
view.ctp
link(’Logout’, array(’controller’ => ‘Users’, ‘action’ => ‘logout’)); ?>
You’ve accessed the secret secure location!
link(’another controller’, array(’controller’ => ‘anotherController2′, ‘action’ => ’someview’)); ?>
————————————
echo html - > is missing in the above code, because of blog restrictions here.
irfan,
1. session is not directly tied to your authentication system. it’s on how you code it that can solve this.
2.there are a few reason why you always get new session id, I think the most common is where you save your cookie domain
And there is no way of keeping session values when switching to another controller?
The Session object is a provided controller, and should work across your entire CakePHP application.
How about if I already have a session, and I want to append more data into that session (shopping cart)?
plz tell me how to use session variables in different controller as i am not getting the value of session variable in different controller.
Asrar:
oana:
as kez say
The Session object is a provided controller, and should work across your entire CakePHP application.
I have the same problem with you. my solved problem is to rename Session.cookie without dot.
like this
Configure::write(’Session.cookie’, ‘CAKE.PHP’);
to
Configure::write(’Session.cookie’, ‘CAKEPHP’);
If you’re having problems with losing Session data when you change between controllers / actions, check your ‘/config/core.php’ file and find the entry for ‘Security.level’ and set it to medium:
Configure::write(’Security.level’, ‘medium’);
The comment on the lines above this entry explains:
“CakePHP session IDs are also regenerated between requests if ‘Security.level’ is set to ‘high’.”
This also keeps users logged in for a bit longer by default.
Thanks, Rich. That seesm to have done the trick for me. In my /config/core.php the property is called CAKE_SECURITY.