Using PHP to Set "SameSite=Strict" Cookies
The "SameSite" attribute enhances the security of cookies by restricting their accessibility from third-party contexts. In April 2016, this feature was introduced in Chrome 51 and Opera 39.
PHP 7.3 and Above
For PHP versions 7.3 and later, you can directly set the "SameSite" attribute using the $options array in the setcookie() function:
<code class="php">setcookie($name, $value, [ 'expires' => time() + 86400, 'path' => '/', 'domain' => 'domain.example', 'secure' => true, 'httponly' => true, 'samesite' => 'None', ]);</code>
The "samesite" element should have a value of "None," "Lax," or "Strict."
PHP Versions Below 7.3
If you are using PHP versions below 7.3, you can employ the following workarounds:
1. Apache Configuration Modification
Add this to your Apache configuration:
Header always edit Set-Cookie (.*) "; SameSite=Lax"
2. Nginx Configuration Modification
Include this in your Nginx configuration:
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
Set cookies using the header method:
<code class="php">header("Set-Cookie: key=value; path=/; domain=example.org; HttpOnly; SameSite=Lax");</code>
4. Bug in setcookie() Method
Use this method with caution as it has been resolved in PHP 7.3:
<code class="php">setcookie('cookie-name', '1', 0, '/; samesite=strict');</code>
Remember to use the appropriate workaround based on your codebase and requirements.
The above is the detailed content of How to Set 'SameSite=Strict” Cookies in PHP: A Guide for Different Versions?. For more information, please follow other related articles on the PHP Chinese website!