PHP Session Sharing Among Subdomains

PHP supports sharing sessions among subdomains which can be very useful for sharing cookies and sessions among multiple web applications.

I wanted my users to remain logged in while navigating from www.example.com to site1.example.com. By default PHP will treat these domains as two separate sites and users would have to login to each subdomain.

All you have to do is to either set the following setting in your php.ini file:
session.cookie_domain = .example.com

Or, set it from within your code before you create your session:
ini_set("session.cookie_domain", ".example.com");
session_start();

4 thoughts on “PHP Session Sharing Among Subdomains”

  1. A couple of things, which most people probably consider trivial (but not to me, unfortunately):

    after:
    ini_set(‘session.cookie_domain’, ‘.example.com’);

    include this:
    session_start();

    but, I had trouble defining a new session name with:
    session_name(‘your_session_name’);
    .. before doing session_start, so I left that line out.

Leave a Reply

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