Wednesday, August 10, 2011

symfony bridge wordpress, share cookie for domain and subdomain, Sharing cookies among all subdomains

There's a common problem of sharing cookies for domain and subdomain.
solution is set domain with and set cookie domain to ''

Sharing cookies among all subdomains

As explained earlier, cookies are not shared among subdomains or between the domain
and the subdomain. In order to set cookies accessible by all subdomains, use the 
following techniques:

  1. While writing the cookie, set the cookie domain to ".domain.ext" so that it applies 
    to all subdomains.

  2. If the cookie domain is set to ".domain.ext", it will not be accessible by a user
    who types in the address without the www before the domain (i.e. http://domain.ext).
    Therefore, redirect all requests without www to http://www.domain.ext.

There are some reported problems with the above approach. It is safe to set the default cookie 
with no domain specified and then set another one with domain as ".domain.ext". In this case 
there is no need for the redirects.
However, remember that session cookies are set by the web server software and you may not
have control over how the cookie domain is set.

real world case:

symfony site on
blog is wordpress on
both sharing same top navigation, so, in blog, the login/logout link should be switched by user current status.
to achieve this, in , we need to know if user has logged in at


1, set permanent redirect, redirect all request to

2, in sfGuardSecurityUser class, add

    // set a cookie for all subdomains
    sfContext::getInstance()->getResponse()->setCookie('wp_bridge', $this->generateRandomKey(), time() + $expiration_age, '/', '');

at bottom of signIn method


sfContext::getInstance()->getResponse()->setCookie('wp_bridge', '', time() - $expiration_age, '/', '');

at bottom of signOut method

3, in wordpress

in my case, find the file : wp-content/themes/mytheme/custom/custome_functions.php

find cookie by

echo 'Hello '.($_COOKIE['wp_bridge']!='' ? $_COOKIE['wp_bridge'] : 'Guest');

DONE, enjoy the bridge.

No comments: