Home > Article > Backend Development > How can I set the \'SameSite\' attribute for cookies in PHP versions prior to 7.3?
How to Use PHP "SameSite=Strict"
In response to the recent changesoutlined in "RFC 6265," which introduced the "Same Site" attribute for controlling cookie access, there has been growing interest in supporting this attribute within PHP.
PHP >= v7.3
For PHP versions 7.3 and above, the ability to set the "Same Site" attribute has been incorporated through the $options array in the setcookie() function. The following example demonstrates how to set the "Same Site" value to "None":
<code class="php">setcookie($name, $value, [ 'expires' => time() + 86400, 'path' => '/', 'domain' => 'domain.example', 'secure' => true, 'httponly' => true, 'samesite' => 'None', ]);</code>
PHP < v7.3
For versions of PHP prior to 7.3, alternative solutions can be employed:
1. Apache Configuration:
By adding the following line to your Apache configuration, you can set the "Same Site" value to "Lax" for all cookies:
Header always edit Set-Cookie (.*) "; SameSite=Lax"
2. Nginx Configuration:
A similar approach is available for Nginx, where you can use the following configuration to set "Same Site" to "Strict" for all cookies:
location / { # your usual config ... # hack, set all cookies to secure, httponly and samesite (strict or lax) proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict"; }
3. Header Method:
As cookies are essentially headers in HTTP requests, you can set them using the header() method:
<code class="php">header("Set-Cookie: key=value; path=/; domain=example.org; HttpOnly; SameSite=Lax");</code>
4. setcookie() Bug Exploit:
There is a known bug in the setcookie() method that allows for setting the "Same Site" value to "Strict" in PHP versions prior to 7.3:
<code class="php">setcookie('cookie-name', '1', 0, '/; samesite=strict');</code>
Note: This bug has been fixed in PHP 7.3.
The above is the detailed content of How can I set the \'SameSite\' attribute for cookies in PHP versions prior to 7.3?. For more information, please follow other related articles on the PHP Chinese website!