【问题标题】:Setting a cookie for two domains为两个域设置 cookie
【发布时间】:2012-05-15 15:40:55
【问题描述】:

我正在尝试为同一个站点设置两个 cookie。 (除了一个是 HTTP,一个是 HTTPS 站点。)

 $cookie_domain_http = parse_url(HTTP_SERVER);
 $cookie_domain_https = parse_url(HTTPS_SERVER);

假设 HTTP_SERVER 包含 http://www.somesite.com 并且 HTTPS_SERVER 包含 https://ssl1.otherdomain.com,我正在使用以下内容。

   setcookie("referrer_key",
     $_GET['referrer'],
     time() + 60*60*24*365,
     $cookie_domain_http['path'], 
     $cookie_domain_http['host']); // Set the cookie for the non-HTTPS version.

if(ENABLE_SSL == "true") {
   setcookie("referrer_key",
     $_GET['referrer'], 
     time() + 60*60*24*365, 
     $cookie_domain_https['path'], 
     $cookie_domain_https['host']); // Set the cookie for HTTPs version.
}

现在第一个setcookie 正在正确设置会话cookie。但是,第二行不会导致它显示。

我如何使用这段代码,特别是 PHP 来做到这一点。

【问题讨论】:

    标签: php session cookies session-cookies zen-cart


    【解决方案1】:

    您只能在一个域中设置一个 cookie,即您的代码正在运行的那个域。最接近的是设置为 somesite.com,在这种情况下,它将被发送到 somesite.com 的所有子域

    您不能在同一段代码中同时在 somesite.com 和 othersite.com 上设置 cookie。

    否则,没有什么可以阻止您为任意域添加 cookie。

    【讨论】:

      【解决方案2】:

      http://php.net/manual/en/function.setcookie.php

      最后还有一个参数,您可以使用它来指定 cookie 是否安全。

      if (ENABLE_SSL == "true") 
        setcookie("referrer_key", 
        $_GET['referrer'], 
        time() + 60*60*24*365, 
        $cookie_domain_https['path'], 
        '.somesite.com', // Parse out the base domain, and put it here with the leading "."
        true); //this is the parameter to set specify a secure cookie
      

      【讨论】:

      • 当我这样做时,它并没有添加到我的 cookie 列表中。
      • 也许更好的答案是使用 .somesite.com 方法。马上查看新答案
      猜你喜欢
      • 2013-06-23
      • 2011-01-28
      • 2018-01-28
      • 2023-04-10
      • 1970-01-01
      • 2013-12-03
      • 2013-07-08
      • 2011-10-09
      相关资源
      最近更新 更多