Getting CakePHP database session data for an external script

I have a requirement for a current project to be able access the CakePHP session data for a script which is running outside of the framework. In normal circumstances this would be as simple as:

session_name('CAKEPHP');
session_start()
print_r($_SESSION);

However in my case the session data is stored in the database. In this situation you need to do a slight bit more to retrieve the session data. Thought I would share the code here for anyone who may need it.

The data is stored in the database in a serialised form and the session_key is essentially stored in a cookie. Therefore the equivalent of the above is:

include_once('../config/database.php');
$db = new DATABASE_CONFIG();

$dbh = mysql_connect($db->default['host'],$db->default['login'],$db->default['password']);
$dbn = mysql_select_db($db->default['database'], $dbh);

$session_qry = mysql_query('SELECT `data` FROM `sessions` WHERE `id`="'.$_COOKIE['CAKEPHP'].'"', $dbh);
$session_data = mysql_result($session_qry, 0, 'data');

session_start();
session_decode($session_data);
print_r($_SESSION);

Hope this comes in useful.

4 thoughts on “Getting CakePHP database session data for an external script

    1. Al Post author

      Well of course Neil, this code is barebones and not production ready :-) Remember kids always sanitize your data!

      Reply
  1. trixdhy

    it’s very helpful, i have a problem to get session value that sent from cake and then i want to retrieve that value from outside of cake and this post is give me the solution .. excellent post

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>