php - 为 www. 取消设置早于特定日期的 Cookie。和非 www 域

标签 php cookies

我想取消我域上的所有 cookie,以便可以为所有用户强制“重新开始”...

下面的代码可以工作,但它不会通过 www.

从域中取消设置 cookie
<?
// Check if this script has run before
if (!isset($_COOKIE['purged_once'])) {

  // Check for old cookies
  if (isset($_SERVER['HTTP_COOKIE'])) {

    $cookies = explode(";", $_SERVER['HTTP_COOKIE']);

    // Iterate and unset all cookies
    foreach ($cookies as $cookie) {

      $fields = explode("=", $cookie);
      $name = trim(fields[0]);

      // unset any cookie for the current path
      setcookie($name, "", time() - 3600);

      // unset the cookie for the root path
      setcookie($name, "", time() - 3600, "/");
    }
  }

  // Set a purged marker for the current path
  setcookie("purged_once", "1", strtotime("+6 months"));
}
?>

该网站通过 .htaccess 规则强制使用非 wwwhttps:

<IfModule mod_rewrite.c>
    # Force HTTPS & NON-WWW
    RewriteEngine On
    RewriteCond %{HTTPS} !=on  [OR]
    RewriteCond %{HTTP_HOST} !^website\.com$ [NC]
    RewriteRule ^ https://website.com%{REQUEST_URI} [R=301,L]
</IfModule>

所以我正在寻找一种在 https://www.website.com 上运行它以强制删除该子域的所有 cookie 的方法/p>

如何实现?

最佳答案

setcookie 函数也接受域名作为参数。当你没有设置域名时,你只为当前域创建cookie。设置域名后,您会为该域及其所有子域创建 cookie。例如,setcookie('cookie_name', 'cookie_value', 3600, '/', 'website.com')example.com 和所有子域创建 cookie ,例如www.example.com, sub.example.com等。一些老的浏览器需要在域名前加一个点来表示你要为子域名设置cookie:

setcookie('cookie_name', 'cookie_value', 3600, '/', '.website.com');

因此,如果您想在取消设置 cookie 时获得一些保证,您可以使用两种方法:

  // unset any cookie for the current path
  setcookie($name, "", time() - 3600, '', 'website.com');
  setcookie($name, "", time() - 3600, '', '.website.com');

  // unset the cookie for the root path
  setcookie($name, "", time() - 3600, "/", 'website.com');
  setcookie($name, "", time() - 3600, "/", '.website.com');

setcookiedomain 参数说明功能:

setcookie ($name, $value, $expire, $path, $domain, $secure, $httponly)

$domain

The (sub)domain that the cookie is available to. Setting this to a subdomain (such as 'www.example.com') will make the cookie available to that subdomain and all other sub-domains of it (i.e. w2.www.example.com). To make the cookie available to the whole domain (including all subdomains of it), simply set the value to the domain name ('example.com', in this case).

Older browsers still implementing the deprecated "RFC 2109" may require a leading . to match all subdomains.

关于php - 为 www. 取消设置早于特定日期的 Cookie。和非 www 域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34389480/

相关文章:

javascript - 三.js : change texture at runtime

javascript - php不向表中插入数据

java - 如何在 Google App Engine (Java) 中启用 session 支持?

python - 是否需要刷新浏览器才能看到新的 cookie?我注意到的令人困惑的问题

javascript - NodeJS - 如何从服务器响应中获取 cookie

php - Paypal 退款交易问题

javascript - 如何用ajax刷新评论?

javascript - Yii2 通过点击链接加载模态

php - 如何在 Goutte 中设置 cookie?

javascript - 使用 fancybox 和 jquery cookie