PHP › Sessions & Cookies
What are the httponly and secure flags on a cookie, and why are they important for protecting session cookies specifically?
IntermediateAnswer
The httponly flag on a cookie tells the browser to prevent that cookie from being accessed through client side JavaScript, which significantly reduces the risk that a cross site scripting attack could steal the cookie's value, while the secure flag ensures the cookie is only ever sent over an encrypted HTTPS connection and never over plain unencrypted HTTP, and since the session cookie holding a visitor's session identifier is essentially the key to their entire authenticated session, protecting it with both of these flags is considered an essential security practice.
session_set_cookie_params([
'httponly' => true,
'secure' => true,
'samesite' => 'Lax',
]);
session_start();Real-world example A banking application configures its session cookie with both the httponly and secure flags enabled, ensuring the session identifier cannot be read by injected malicious JavaScript and is never accidentally transmitted over an insecure connection.