Search code examples
phpapachegoogle-chromesessioncookies

Rename PHP session cookie with __Secure-/__Host- prefix


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?


Solution

  • I'm not familiar with Cookie Prefixes but PHP should support it out of the box:

    <?php
    
    session_name('__Secure-PHPSESSID');
    session_start();
    

    Set-Cookie