PHP setting a Session-Cookie with samesite
As of PHP 7.3 you can throw an options array into set_cookie_params that supports SameSite.
session_set_cookie_params([
'lifetime' => $cookie_timeout,
'path' => '/',
'domain' => $cookie_domain,
'secure' => $session_secure,
'httponly' => $cookie_httponly,
'samesite' => 'Lax'
]);
On PHP <7.3 you can add the SameSite parameter adding it in the "path" param.
session_set_cookie_params([
'lifetime' => $cookie_timeout,
'path' => '/;SameSite=none', // <-- this way!
'domain' => $cookie_domain,
'secure' => $session_secure,
'httponly' => $cookie_httponly,
'samesite' => 'Lax'
]);
Adapted from SilverShadow answer, but fixing the syntax for php <7.3,
since session_set_cookie_params()
can't take an array as single parameter until preciselly 7.3, instead each parameter needs to be set.
and autodetecting php version for the correct option so you can use it even if you later upgrade to 7.3:
// set as your own needs:
$maxlifetime = 0;
$path = '/';
$domain = '';
$secure = false;
$httponly = false;
$samesite = 'lax'; // here is what we need
if(PHP_VERSION_ID < 70300) {
session_set_cookie_params($maxlifetime, $path.'; samesite='.$samesite, $domain, $secure, $httponly);
} else {
// note I use `array()` instead of `[]` to allow support of php <5.4
session_set_cookie_params(array(
'lifetime' => $maxlifetime,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httponly' => $httponly,
'samesite' => $samesite
));
}