Monday, May 16, 2011

PHP Session Cookie Multiple Domains

If you are looking to keep session variables for your site users who might be using multiple sub-domains on your site there is a relatively easy way to set this up though not well documented till now. You want xxx.domain.com, www.domain.com and maybe even just domain.com to share the same session? Session Cookies Problem Before I go on, I’m assuming you store your session id in cookies. If you don’t then this won’t help you, sorry. If you are then I can enlighten you with the problem with sharing sessions. Simply put, the cookies that store your session ID is host_name specific. Thus two different cookies are used to store domain.com and www.domain.com. Furthermore, to the best of my knowledge and what would seem to be for security reasons, your browser and php for that matter won’t let you read other domain’s cookies. Make’s sense really. Wouldn’t want malicious.cracker.com reading your bank session cookies while you’re checking your balance. My Fix So you need to change the php session configuration option for session.cookie_domain from the default of “” (which inserts your hostname) to: “.domain.com” You can do this with: session_set_cookie_params() before doing your session_start() or if you have php start your sessions for you automatically you might consider throwing: php_value session.cookie_domain ".domain.com"into the .htaccess file for the site. If you put the .htaccess file in the directory for xxx.domain.com then all sessions started on xxx.domain.com will be shared on all other domains like www.domain.com. This means however that sessions started in www.domain.com won’t carry over unless the .htaccess file is also present in it’s root directory. Important Note The first dot in “.domain.com” is not always nessesary however for support of all browsers it is suggested.

No comments: