Zend Framework and Session Cookies across Subdomains

Posted on September 24th, 2008
Published in PHP, Zend Framework
Tagged with: , , , ,

Session support in PHP consists of a way to preserve certain data across subsequent accesses. Each visitor accessing the web site is assigned a unique id, the session id. This session id is either stored in a cookie or propagated in the url. The best solution is to store it in a cookie.

The cookie used to store the session id sets, by default, the cookie domain to the current domain. This means that if you are visiting www.domain.com, the session id will be stored in a cookie bounded to the domain www.domain.com. This behavior leads to a problem: if your site uses multiple subdomains, the session won’t be shared between the site’s subdomains.

To solve this problem you have to share the cookie between all subdomains, setting its domain it to “.domain.com”. The following code shows how to change the session cookie domain with Zend Framework:

Zend_Session::start(array('cookie_domain' => '.domain.com'));

Browers compatibility

The prefix dot in “.domain.com” is not always necessary, but it’s highly recommended to support all browsers.

References

Leave a Reply