Sharing the same login with multiple subdomains using browser cookies.

Deepak vaishnav
2 min readOct 25, 2022

--

Sometimes we need to share the same login session of a user throughout all website subdomains like www.example.com to blog.example.com or shop.example.com.

To achieve this we can use The Domain attribute of the cookie which is the fifth parameter in setcookie function in PHP.

$domain = '.example.com';
setcookie($cookieName, $cookieValue, time() + 3600, ‘/’, $domain);

and for JavaScript, we need to define a function for setting a cookie that includes a domain attribute.

function setCookie(a, b, c) {
var domain = 'example.com';
var d = new Date();
d.setTime(d.getTime() + c * 60 * 60 * 1000);
var e = 'expires=' + d.toGMTString();
var f = 'domain=' + domain + ';path=/';
document.cookie = a + '=' + b + '; ' + e + ';' + f;
}

When a user login into the main domain we have to store a login token in cookies using any encryption technique.

if($login == true){
$loginToken = md5(time());
// TODO :: Store this token into Databse
// Store this token into Cookie
$domain = '.example.com';
setcookie('_loginToken', $loginToken, time() + 3600, ‘/’, $domain); /* expire in 1 hour */
}

Now we need to get the cookie by using the super global variable $_COOKIE[‘_loginToken’] in PHP.

$loginToken = $_COOKIE['_loginToken'];

get data from the database and set a session for the user.

if(isset($_COOKIE['_loginToken']) && $_COOKIE['_loginToken']!=''){  
$loginToken = $_COOKIE['_loginToken'];
// TODO :: get User from database by using login token
// TODO :: Set session of user
}

By using these steps Same login can be shared throughout various domains.

--

--