Module 23: CookiesIntermediate35 min read
HTTP Cookies, Secure Flags (HttpOnly, Secure, SameSite) & Lifecycle
Create, update, and delete cookies securely in PHP using Secure, HttpOnly, and SameSite options to defend against XSS theft and CSRF.
Key Takeaways & Core Concepts
- `httponly => true`: Blocks JavaScript
document.cookieaccess (protects against XSS). - `secure => true`: Transmits cookie only over HTTPS.
HTTP Cookies, Secure Flags (HttpOnly, Secure, SameSite) & Lifecycle
### 1. Cookie Security Flags Always pass an options array to setcookie():
- `httponly => true`: Blocks JavaScript
document.cookieaccess (protects against XSS). - `secure => true`: Transmits cookie only over HTTPS.
- `samesite => 'Lax'` (or
'Strict'): Mitigates CSRF.
1. Secure setcookie() Options Array (PHP 7.3+)
1<?php
2$cookieOptions = [
3 'expires' => time() + 3600,
4 'path' => '/',
5 'secure' => true,
6 'httponly' => true,
7 'samesite' => 'Lax',
8];
9echo "Cookie configured for 1 hour with SameSite=" . $cookieOptions['samesite'] . "\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: Demonstrates the modern associative options array passed to `setcookie()`.
Practice & AssessmentPHP Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)