Sharing Session State Across CakePHP Applications

This is a pretty simple tip, but I thought I might want to document this somewhere like the gotcha page.
I'll show you how to share session state across multiple CakePHP applications. It's as easy as 1-2-3.

Let's say we have two sites, siteA.com and siteB.com. A user is browsing siteA.com and we want him (or her) transferred to siteB.com. The user should be already authenticated before jumping to siteB.com.

There are some settings you must first configure:

  • Make sure that you have set 'Security.level' to 'low' on siteB.com. Notice that 'high' and 'medium' will mark the embedded session ID as invalid.
  • Set the session handling method ('Session.save' in app/config/core.php) to either 'php' or 'database'. Both applications must have the same session handling method and access to the same session storage (and therefore the same session).
  • Use the same Security.salt (/app/config/core.php) for each application.

In our view template on siteA.com, append the session ID to the link like the following:

echo $html->link('Go to siteB.com',
"http://siteB.com/tests/index?sid=" . $session->id()
);

On the other end (siteB.com), use $this->Session->id($this->params['url']['sid']) in the beforeFilter method of your controller:

function beforeFilter() {
if (!empty($this->params['url']['sid'])) {
$this->Session->id($this->params['url']['sid']);
}
}

When the user clicks the link on siteA.com, it'll redirect with the session id as parameter and instantiate a new session.

If you need a more secure way, go check the next post “A More Secure Way to Transfer Session State Between CakePHP Applications