PHP Cookies across multiple sub domains

Here's how to make the browser store cookies across multiple sub domains.

The example I have used is for my site. The cookie given to the browser will be used for any *.dtbaker.com.au address. The PHP code creates a new session with a random session id, that session id is stored in the cookie, and the cookie is sent to the browser. Next time the browser sends a requests, it will send the cookie that contains the session id.

Here's the PHP code:

define("SESSION_NAME","S_DTBAKER");
if(!isset($_COOKIE[SESSION_NAME])){
        // new session id
        session_id( md5 ( uniqid ( microtime () ) ) );
        session_name ( SESSION_NAME );
        session_start();
        // send cookie - change dtbaker.com.au to your domain name
        setcookie( SESSION_NAME, session_id(), 0, '/', '.dtbaker.com.au');
}else{
        session_id( $_COOKIE[SESSION_NAME] );
        session_name( SESSION_NAME );
        session_start();
}
Comments
  1. Hello,
    this is a very good example, but how can I unset the session?

    session_start();
    session_unset("sessid");
    session_destroy("sessid");
    setcookie ("sessid", session_id(), time() -3600, '/', '.site.com'); is not working...


    1. session_unset();
      and
      session_destroy();
      should do the trick



Leave a Comment

Yes, send me an email when a new comment is posted.

The avatars shown next to comments are Gravatars. Click here to get a Gravatar account for free and any other site that supports it will show your avatar too!