Set cookie on multiple domains with PHP or JavaScript

I have 3 domains that are themed the same. If somebody chooses a different theme, I want it to propagate across all 3 domains so their experience stays the same.

I was planning to accomplish this by setting a cookie on domain1, redirect to domain2 where the cookie is set, redirect to domain3 where the cookie is set, redirect back. Since the information doesn’t need to be secure or protected, this will work fine with no real problems.

I hate the idea 3 redirects just to set a cookie on each domain and was looking for something a little more elegant.

Do what Google is doing. Yes, Google is doing this same trick to login the user to YouTube and other Google services which are on different domains.

Create a PHP file that sets the cookie on all 3 domains. Then on the domain where the theme is going to set, create a HTML file that would load the PHP file that sets cookie on the other 2 domains. Example:

      <p>Please wait.....</p>
      <img src="" />
      <img src="" />

Then add an onload callback on body tag. The document will only load when the images completely load that is when cookies are set on the other 2 domains. Onload Callback :

   function loadComplete(){
      window.location="";//URL of domain1
<body onload="loadComplete()">


We set the cookies on the other domains using a PHP file like this :

   setcookie("theme", $_GET['theme'], time()+3600);

Now cookies are set on the three domains.

Source – My Blog

You could include the other two domains in iFrames. For more information search for “third party cookies”. However depending on the browser settings, the user might not accept third party cookies. There are some other ideas here: What’s your favorite cross domain cookie sharing approach?

Read More:   How to handle 'undefined' in JavaScript [duplicate]

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts