使用 PHP 或 JavaScript 在多个域上设置 cookie

2021-12-21 00:00:00 cookies php javascript setcookie

我有 3 个主题相同的域.如果有人选择了不同的主题,我希望它在所有 3 个域中传播,以便他们的体验保持不变.

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.

我打算通过在 domain1 上设置 cookie 来实现这一点,重定向到设置了 cookie 的 domain2,重定向到设置了 cookie 的 domain3,然后重定向回来.由于信息不需要安全或受保护,因此这将正常工作,不会出现实际问题.

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.

我讨厌 3 重定向只是为了在每个域上设置一个 cookie 并且正在寻找更优雅的东西.

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

推荐答案

做 Google 正在做的事情.是的,Google 正在使用相同的技巧让用户登录 YouTube 和不同域中的其他 Google 服务.

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.

创建一个 PHP 文件,在所有 3 个域上设置 cookie.然后在要设置主题的域上,创建一个 HTML 文件,该文件将加载在其他 2 个域上设置 cookie 的 PHP 文件.示例:

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:

<html>
   <head></head>
   <body>
      <p>Please wait.....</p>
      <img src="http://domain2.com/setcookie.php?theme=whateveryourthemehere" />
      <img src="http://domain3.com/setcookie.php?theme=whateveryourthemehere" />
   </body>
</html>

然后在 body 标签上添加一个 onload 回调.该文档仅在图像完全加载时加载,即在其他 2 个域上设置 cookie 时.加载回调:

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 :

<head>
   <script>
   function loadComplete(){
      window.location="http://domain1.com";//URL of domain1
   }
   </script>
</head>
<body onload="loadComplete()">

setcookie.php

我们使用 PHP 文件在其他域上设置 cookie,如下所示:

setcookie.php

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

<?php
if(isset($_GET['theme'])){
   setcookie("theme", $_GET['theme'], time()+3600);
}
?>

现在 cookie 设置在三个域上.

Now cookies are set on the three domains.

来源 - 我的博客

相关文章