本文目录导读:

在 PHP 中设置 SameSite Cookie 属性有几种方法,主要取决于你使用的 PHP 版本和设置方式。
PHP 7.3+ 原生支持
PHP 7.3 开始,setcookie() 和 setrawcookie() 函数支持 SameSite 参数:
使用数组方式(推荐)
setcookie(
'cookie_name',
'cookie_value',
[
'expires' => time() + 3600,
'path' => '/',
'domain' => 'example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax' // Lax | Strict | None
]
);
使用传统参数方式
setcookie(
'cookie_name',
'cookie_value',
time() + 3600, // expires
'/', // path
'example.com', // domain
true, // secure
true, // httponly
['samesite' => 'Lax'] // 需要放在最后
);
PHP 7.3 之前的兼容方案
对于老版本 PHP,可以通过修改 header() 来实现:
// 直接在 header 中设置
header('Set-Cookie: cookie_name=cookie_value; expires=Timestamp; path=/; samesite=Lax');
// 或者动态生成
$cookie_name = 'cookie_name';
$cookie_value = 'cookie_value';
$expires = time() + 3600;
$path = '/';
$domain = 'example.com';
header(
'Set-Cookie: ' . $cookie_name . '=' . urlencode($cookie_value) .
'; expires=' . gmdate('D, d M Y H:i:s T', $expires) .
'; path=' . $path .
'; domain=' . $domain .
'; samesite=Lax'
);
使用 session 设置 SameSite
对于 session cookie:
PHP 7.3+
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => '',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
session_start();
老版本 PHP
// 在 session_start() 之前
header('Set-Cookie: PHPSESSID=' . session_id() . '; path=/; samesite=Lax; Secure; HttpOnly');
session_start();
各值说明
| 值 | 说明 |
|---|---|
Strict |
完全禁止跨站请求携带 Cookie |
Lax |
允许部分安全的跨站 GET 请求携带(默认推荐) |
None |
允许所有跨站请求携带(需配合 Secure,且 HTTPS) |
完整示例
class CookieHelper {
public static function set($name, $value, $expire = 0, $path = '/', $domain = '', $secure = false, $httponly = true, $samesite = 'Lax') {
if (PHP_VERSION_ID >= 70300) {
setcookie($name, $value, [
'expires' => $expire,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httponly' => $httponly,
'samesite' => $samesite
]);
} else {
// 兼容老版本
header(
'Set-Cookie: ' . $name . '=' . urlencode($value) .
'; expires=' . ($expire ? gmdate('D, d M Y H:i:s T', $expire) : '') .
'; path=' . $path .
($domain ? '; domain=' . $domain : '') .
($secure ? '; Secure' : '') .
($httponly ? '; HttpOnly' : '') .
'; samesite=' . $samesite
);
}
}
}
// 使用
CookieHelper::set('user_token', 'abc123', time() + 3600, '/', '', true, true, 'Lax');
注意事项
SameSite=None必须配合Secure- 浏览器兼容性:Chrome 51+、Firefox 60+、Safari 12.1+ 支持
- 安全建议:业务非必要跨站用户 Cookie 建议设置为
Strict或Lax
根据你的 PHP 版本选择合适的实现方式即可。