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 www.example.com and set cookie domain to '.example.com'
reference: 


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 example.com
blog is wordpress on blog.example.com
both sharing same top navigation, so, in blog, the login/logout link should be switched by user current status.
to achieve this, in blog.example.com , we need to know if user has logged in at example.com

steps:

1, set permanent redirect, redirect all example.com request to www.example.com

2, in sfGuardSecurityUser class, add

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

at bottom of signIn method

  add

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

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.

Monday, August 08, 2011