I'm trying to rename my PHP session cookie from PHPSESSID
to __Secure-PHPSESSID
as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#Examples.
Since PHP does not offer this mechanism, I am doing it through Apache server configuration:
RequestHeader edit Cookie ^__Secure-PHPSESSID(.*)$ PHPSESSID$1
Header edit Set-Cookie ^PHPSESSID(.*)$ __Secure-PHPSESSID$1
Header edit Set-Cookie ^(.*)(?<!SameSite=Strict)(?<!SameSite=Lax)$ "$1;SameSite=Lax"
This works correctly in Firefox, Edge, and Safari, but not Chrome. On Chrome, I can see that the cookie is set with the correct name and flags but I cannot log in to my site.
Upon login, the output of var_dump($_SESSION['internal']['user_name'])
is NULL
on Chrome but shows the correct username on Firefox and other browsers. I can also see that the session ID is being regenerated every time I try to log in and the value is set in the __Secure-PHPSESSID
cookie.
I tried removing the SameSite
flag (line 3 above) and it still does not work.
Any ideas?
PHP does indeed offer this mechanism. You can change it in php.ini
. Just set this and restart the site:
session.name = __SECURE-PHPSESSID
To confirm it's right, restart your browser to clear previous session cookies.
As for Chrome not letting you log in, this page may give you some clues (see "Option Secure" and "Prefixes" sections): https://www.mon-code.net/post/108/Secure-cookie-of-you-web-application-with-PHP-or-Symfony
They are not well known, but supported by all browsers except those of Microsoft. With prefixes, it's possible to force the browser to not accept a cookie if it's misconfigured. There are two prefixes "
__Secure-
" and "__Host-
".__Secure-
forces the developer to add the secure flag to his cookie, otherwise it will be ignored by the browser.
setcookie('__Secure-user_id', 10, 0, '/', 'orion.dev', true);
__Host-
is more restrictive, cookie must have the secure flag but also path to root and blank domain.
setcookie('__Host-user_id', 10, 0, '/', '', true);
I'm not familiar with Cookie Prefixes but PHP should support it out of the box:
<?php
session_name('__Secure-PHPSESSID');
session_start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With