Blog about Web Programming and Electronics
💬 👤
back Back to blog
WEB (HTML, CSS, PHP)

Understanding and Setting the SameSite Attribute for Cookies

Browsers have recently tightened security. If you see a warning about the SameSite attribute on your site, it means you must explicitly tell the browser how to handle your cookies in different contexts.

What is SameSite anyway?

The SameSite attribute in HTTP cookie headers controls when a cookie is sent to the server. Its main purpose is protection against:

  • CSRF attacks: Prevents malicious sites from using your session.
  • Information leakage: Limits cookie sharing between different domains.

Possible attribute values

  1. Strict: The strictest setting. The cookie is sent only if the request comes from the same domain.
  2. Lax: Default safe setting. The cookie is sent during navigation within the same domain and at some external links, but not in iframes.
  3. None; Secure: The cookie is sent always, even in third-party contexts. Mandatory requires a secure HTTPS connection.

How to fix this in code?

PHP (7.3+)

setcookie("PH_HPXY_CHECK", "value", [
"SameSite" => "None",
"Secure" => true, // Required for None
"HttpOnly" => true
]);

JavaScript

document.cookie = "PH_HPXY_CHECK=value; SameSite=None; Secure";

Nginx / Apache

If you\'re setting cookies at the server level:

# Nginx
add_header Set-Cookie "PH_HPXY_CHECK=value; Path=/; SameSite=None; Secure";

# Apache
Header always add Set-Cookie "PH_HPXY_CHECK=value; Path=/; SameSite=None; Secure"
back Back to blog