php/js cookie共享跨域的问题

本文详细介绍了如何在相同顶级域名和不同顶级域名下实现Cookie的共享。对于相同顶级域名,只需在顶级域名下设置Cookie;而对于不同顶级域名,需要设置httpOnly、secure和sameSite属性,特别是sameSite需设为None。示例代码分别展示了PHP和JavaScript的实现方式。
摘要由CSDN通过智能技术生成

记录一下最近做的一个cookie共享的需求.,有两种情况:

第一种:相同的顶级域名的情况下,只需要将cookie写在顶级域名下,该域名下的所有子域名都能访问到了。如 PHP:

//xxx.com   前面不能加.  (生成的cookie的domain是 .xxx.com)
setcookie('test','value',time()+60*60*24*30,'/','xxxx.com');

//xxx.com 的所有子域名就 都能获取到了
$_COOKIE['test'];

JS的设置和php类似:

//存储cookie,这里的域名必须是顶级域名
setCookie('test','value','xxx.com','20')
function setCookie(cName, value,domain,expireDate) {
	const exDate = new Date();
	exDate.setDate(exDate .getDate() + expireDate);
	document.cookie = cName + "=" + decodeURIComponent(value) + (expireDate== null ? "" : ";expires=" + exDate.toUTCString()) + ";path=/;domain="+domain;
}
 
//获取cookie
getCookie('test')
function getCookie(key) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[-.+*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
}

第二种:两个顶级域名不同的站点,需要在设置cookie的时候设置httpOnly、secure、sameSite;比如A设置了cookie,B可以通过jsonp的方式就能取到了。sameSite必须设置为None,默认是空。如PHP:

php>=7.3版本可以直接设置

setcookie('test','value',[
    'expires'=>time()+60*60*24*30,
    'path'=>'/',
    'domain'=>'xxx.com',
    'httponly'=>true,
    'secure'=>true,
    'samesite'=>'None'
]);

php<7.3

function samesite_setcookie($name, $value, array $options)
{
    $header = 'Set-Cookie:';
    $header .= rawurlencode($name) . '=' . rawurlencode($value) . ';';
    if (isset($options['expires'])) {
        $header .= 'expires=' . \gmdate('D, d-M-Y H:i:s T', $options['expires']) . ';';
    }
    if (isset($options['expires'])) {
        $header .= 'Max-Age=' . max(0, (int) ($options['expires'] - time())) . ';';
    }
    if (!empty($options['path'])) {
        $header .= 'path=' . $options['path']. ';';
    }
    if (!empty($options['domain'])) {
        $header .= 'domain=' . rawurlencode($options['domain']) . ';';
    }
    if (!empty($options['secure'])) {
        $header .= 'Secure;';
    }
    if (!empty($options['httponly'])) {
        $header .= 'HttpOnly;';
    }
    if (!empty($options['samesite'])) {
        $header .= 'SameSite=' . rawurlencode($options['samesite']);
    }
    header($header, false);
    $_COOKIE[$name] = $value;
}

samesite_setcookie('test', 'value', [
    'expires' => time()+60*60*24*30,
    'domain' => 'xxx.com',
    'httponly' => true,
    'samesite' => 'None',
    'secure' => true,
    'path' => '/'
]);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为天空着色

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值