As of PHP 7.3.0 the
setcookie()
method
supports the SameSite
attribute in its options and will accept None
as a
valid value.
// Set a same-site cookie for first-party contexts
setcookie('cookie1', 'value1', ['samesite' => 'Lax']);
// Set a cross-site cookie for third-party contexts
setcookie('cookie2', 'value2', ['samesite' => 'None', 'secure' => true]);
For earlier versions of PHP, you can also set the
header()
directly:
// Set a same-site cookie for first-party contexts
header('Set-Cookie: cookie1=value1; SameSite=Lax', false);
// Set a cross-site cookie for third-party contexts
header('Set-Cookie: cookie2=value2; SameSite=None; Secure', false);
For Session Cookie , you can set into session_set_cookie_params
method.
PHP 7.3.0 introduced new attributes for samesite.
if (PHP_VERSION_ID >= 70300) {
session_set_cookie_params([
'lifetime' => $cookie_timeout,
'path' => '/',
'domain' => $cookie_domain,
'secure' => $session_secure,
'httponly' => $cookie_httponly,
'samesite' => 'Lax'
]);
} else {
session_set_cookie_params(
$cookie_timeout,
'/; samesite=Lax',
$cookie_domain,
$session_secure,
$cookie_httponly
);
}