Set Cookie on Cross Domains


If you want to set cookie on your domain, you can do this by few lines of codes just using JS. But the problem arises when you want to set cross domain cookie(s).


Say, you have three domains.


Now when someone enters to, I set a cookie (say, visited:nixon's site) for the domain. So that I can show some info based on cookie.
Now I also need to set same cookie to my others domains. So that I can serve same info as in those domains too.

Now the question is how to set cookie from a domain to some other domains?

We can't send a ajax request from one domain to another domain since mordern browser will block these request for cross domain requesting.


There could be many solutions for this kind of problem. But I have find out a simple solution. I hope it'll save some other developers valuable time.

Say, the sites in three domains are running in PHP.

First I place a PHP code in a script called cookies.html?php setcookie("visited", "nixon's site", time()+3600); ?>

Now on the domain the HTML code will be look like the following code

<!DOCTYPE html>
   //place set cookie for own domain here

  <!-- setting cookies to other domains -->
  <img src="" style="display:none;" />
  <img src="" style="display:none;" />
  <!-- setting cookies to others domains ends -->

  <!-- place other htmls here -->

So, when someone visits,it will request a pages from other domain as images. As the pages are not images they will set cookies for those domain in the browser. And the browser allows it too.

This is how Google, Microsoft etc. set cookies for their multiple domains. Say you logged into, it'll set cookie like this to, etc.

comments powered by Disqus