PHP setting a Session-Cookie with samesite

萝らか妹 提交于 2020-05-15 07:57:05

问题


I currently have a PHP script that sets the sametime cookie as follows:

    session_set_cookie_params($cookie_timeout, $cookieParams["path"], $cookie_domain, $session_secure, $cookie_httponly);

I want to add samesite="Lax" to the above statement by adding an extra parameter where ($cookie_samesite="Lax")

    session_set_cookie_params($cookie_timeout, $cookieParams["path"], $cookie_domain, $session_secure, $cookie_httponly, $cookie_samesite);

The new output of the statement would look like

1800, /, ".vasports.com.au", 1, 1, "Lax"

Is this the correct format for the samesite parameter?

NOTE: I do not have a PHP7.3 installed yet. Hence I can't test this properly. And I've referred to PHP doco for "session_set_cookie_params". I have also checked

PHP setcookie "SameSite=Strict"?


回答1:


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'
]);



回答2:


After some further research ...

  1. Get current parameters first.
  2. Then change the parameters as required, in this case [samesite]="Lax".
  3. Set the cookie.
    $cookieParams = session_get_cookie_params();
    $cookieParams[samesite] = "Lax";
    session_set_cookie_params($cookieParams);

Check your 'set-cookie:' header and you should now see the text 'SameSite=Lax' at the end like this.

    set-cookie: ssid=b930bc608a911781f459a4f46b2c513d; expires=Wed, 16-Oct-2019 10:48:49 GMT; Max-Age=1800; path=/; secure; HttpOnly; SameSite=Lax


来源:https://stackoverflow.com/questions/58317981/php-setting-a-session-cookie-with-samesite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!