php设置samesite cookie,支持所有PHP版本。
PHP 7.3 的setcookie函数已经支持samesite属性,但对于7.3以下版本,可以用以下函数代替:
<?php
$options = [
'expires' => time()+18400,
'domain' => 'localhost',
'httponly' => false,
'samesite' => 'Lax',
'secure' => false,
'path' => '/'
];
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('hahaha', 'tttttt', $options);
原创文章,转载请注明来自Lenix的博客,地址https://blog.p2hp.com/archives/6555
相关博文
php设置samesite cookie,有效防止CSRF
