How to Set 'SameSite=Strict” Cookies in PHP: A Guide for Different Versions?

Linda Hamilton
Release: 2024-10-25 05:53:02
Original
194 people have browsed it

How to Set “SameSite=Strict” Cookies in PHP: A Guide for Different Versions?

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>
Copy after login

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"
Copy after login

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";
}
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!