Search code examples
phpcookies

Cookies not visible from external link to PHP page


I have a PHP webpage (let's say https:://example.com/page1.php) that uses cookies.

When I go to that page, I can see that PHP can see the cookies ($_COOKIE['xxx']), but when I click on a link from a Yahoo! email to the same page, I can see that PHP cannot see them; if I click F5 to refresh the page, they are still not visible to PHP, but if I were to click on the location bar and press return then the cookies become visible to PHP.

If I click on a similar link from within the example.com domain, I see that the cookies are visible to PHP.

There's very little to say about the code...

 <?php
        foreach ($_COOKIE as $k=> $v) echo "<LI>$k=$v";
 ?>

and the javascript that sets the cookie earlier...

function setCookie(name, value) {
    var expires = "";
    var days=9999;
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    expires = "; expires=" + date.toUTCString();

    var val = (value || "") + expires + "; secure; path=/; samesite=strict";
    document.cookie = name + "=" + val;
}

(the cookies I'm using are set earlier in the site, and have a Domain = "example.com", an expiry date many years ahead, Secure, and SameSite=Strict).

Can anyone explain what is going on?


Solution

  • Thanks CBroe, it looks like that gave me the clue - SameSite=Strict was causing this problem.

    function setCookie(name, value, samesite) {
       if ( samesite==undefined ) samesite='lax';   <--------------- strict, lax or none
       var days=9999;
       var date = new Date();
       date.setTime(date.getTime() + (days*24*60*60*1000));
       var expires = "; expires=" + date.toUTCString();
    
       var val = (value || "") + expires + "; secure; path=/; samesite="+samesite;
       document.cookie = name + "=" + val;
    }