0
0
PHPprogramming~15 mins

Cookie expiration and security in PHP - Deep Dive

Choose your learning style9 modes available
Overview - Cookie expiration and security
What is it?
Cookies are small pieces of data stored by a web browser to remember information about a user. Cookie expiration controls how long a cookie stays on the user's device before it is deleted. Security settings on cookies help protect sensitive data from being stolen or misused by attackers. Together, expiration and security settings ensure cookies work safely and effectively.
Why it matters
Without proper cookie expiration, cookies could stay forever, risking outdated or sensitive data exposure. Without security settings, cookies can be stolen or manipulated by attackers, leading to privacy breaches or unauthorized access. Proper cookie management protects users and websites from many common security problems and helps maintain trust.
Where it fits
Learners should first understand what cookies are and how they work in web browsers. After mastering expiration and security, they can learn about session management, authentication, and secure web development practices.
Mental Model
Core Idea
Cookie expiration and security settings control how long cookies live and who can safely access them to protect user data.
Think of it like...
Think of a cookie like a note you leave on a friend's door. Expiration is when you decide to remove the note so it doesn't stay forever. Security settings are like sealing the note in an envelope so only your friend can read it and no one else can peek.
┌───────────────┐
│   Cookie      │
│───────────────│
│ Data          │
│ Expiration →  │
│ Security →    │
└─────┬─────────┘
      │
      ▼
┌───────────────┐
│ Browser stores│
│ cookie until  │
│ expiration or │
│ deleted       │
└───────────────┘
Build-Up - 6 Steps
1
FoundationWhat is a cookie and its purpose
🤔
Concept: Introduce the basic idea of cookies as small data stored by browsers to remember user info.
A cookie is a tiny file saved by your web browser when you visit a website. It can store things like your login name or preferences so the website remembers you next time. Cookies help websites provide a smoother, personalized experience.
Result
You understand cookies as simple data holders that help websites remember you.
Knowing what cookies are and why they exist is the foundation for understanding how expiration and security settings affect them.
2
FoundationHow cookie expiration works
🤔
Concept: Explain how cookies have a lifetime after which browsers delete them automatically.
When a website sets a cookie, it can tell the browser when the cookie should expire. This is done by setting an expiration date or a maximum age. After that time, the browser removes the cookie. If no expiration is set, the cookie lasts only until the browser closes (session cookie).
Result
You know cookies don't last forever and can be set to expire at a specific time.
Understanding expiration helps you control how long user data stays stored, which is key for privacy and freshness.
3
IntermediateSetting cookie expiration in PHP
🤔Before reading on: Do you think cookie expiration is set as a date string or as a number of seconds? Commit to your answer.
Concept: Learn how to set cookie expiration time using PHP's setcookie function.
In PHP, you set a cookie with setcookie(name, value, expire). The expire parameter is a timestamp (seconds since 1970) when the cookie should expire. For example, time() + 3600 sets the cookie to expire in 1 hour. If you omit expire, the cookie lasts only for the session.
Result
You can control cookie lifetime precisely in PHP by setting the expire timestamp.
Knowing how to set expiration timestamps lets you manage cookie lifetimes programmatically for better user experience and security.
4
IntermediateCookie security flags explained
🤔Before reading on: Do you think the Secure flag allows cookies over HTTP or only HTTPS? Commit to your answer.
Concept: Introduce cookie flags like Secure, HttpOnly, and SameSite that protect cookies from theft or misuse.
Secure flag means the cookie is sent only over HTTPS, protecting it from being sent on insecure connections. HttpOnly flag prevents JavaScript from accessing the cookie, reducing risk from cross-site scripting attacks. SameSite flag controls if cookies are sent with cross-site requests, helping prevent cross-site request forgery.
Result
You understand how cookie flags add layers of protection to cookies.
Recognizing these flags helps you secure cookies against common web attacks and protect user data.
5
AdvancedImplementing secure cookies in PHP
🤔Before reading on: Do you think setting Secure and HttpOnly flags requires extra parameters in setcookie or separate functions? Commit to your answer.
Concept: Learn how to set cookie security flags properly in PHP using the options array in setcookie.
Since PHP 7.3, setcookie accepts an options array where you can set 'secure' => true, 'httponly' => true, and 'samesite' => 'Strict' or 'Lax'. Example: setcookie('user', 'abc', [ 'expires' => time() + 3600, 'secure' => true, 'httponly' => true, 'samesite' => 'Strict' ]); This ensures the cookie is sent only over HTTPS, inaccessible to JavaScript, and restricted in cross-site requests.
Result
You can create cookies that are safer by using modern PHP features.
Using the options array is the modern, clear way to set multiple security flags at once, reducing mistakes.
6
ExpertCommon pitfalls and subtle security risks
🤔Before reading on: Do you think setting Secure flag alone fully protects cookies from theft? Commit to your answer.
Concept: Explore subtle issues like missing Secure flag on HTTP pages, improper SameSite usage, and cookie theft vectors.
Even if Secure is set, if your site serves some pages over HTTP, cookies can leak. SameSite 'Lax' is default but may allow some cross-site requests; 'Strict' is safer but can break functionality. HttpOnly protects from JavaScript theft but not from network sniffing if Secure is missing. Also, cookie expiration far in the future can increase risk if stolen.
Result
You understand that cookie security requires a combination of settings and careful site design.
Knowing these subtle risks helps prevent false security assumptions that lead to vulnerabilities in real-world applications.
Under the Hood
When a server sends a Set-Cookie header, the browser stores the cookie with its data, expiration time, and flags. On each request to the cookie's domain and path, the browser sends the cookie back if it is not expired and meets security rules. Flags like Secure restrict sending cookies only over HTTPS connections. HttpOnly prevents client-side scripts from reading cookies. SameSite controls cross-site sending behavior. Expired cookies are deleted automatically by the browser.
Why designed this way?
Cookies were designed to be simple key-value stores for stateful web sessions. Expiration allows automatic cleanup to avoid stale data. Security flags were added later as web attacks evolved, to protect cookies from interception and cross-site attacks. The design balances usability, backward compatibility, and security by letting developers choose appropriate flags.
┌───────────────┐
│ Server sends  │
│ Set-Cookie    │
│ header with   │
│ data + flags  │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Browser stores│
│ cookie with   │
│ expiration &  │
│ security flags│
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ On requests,  │
│ browser sends │
│ cookie if not │
│ expired and   │
│ flags allow   │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does setting the Secure flag allow cookies to be sent over HTTP? Commit yes or no.
Common Belief:Setting the Secure flag means cookies can be sent over both HTTP and HTTPS safely.
Tap to reveal reality
Reality:Secure flag restricts cookies to HTTPS only; they are never sent over HTTP.
Why it matters:If you think Secure allows HTTP, you might expose cookies on insecure connections, risking theft.
Quick: Do HttpOnly cookies prevent all types of cookie theft? Commit yes or no.
Common Belief:HttpOnly cookies cannot be stolen because JavaScript cannot access them.
Tap to reveal reality
Reality:HttpOnly protects only against JavaScript access, but cookies can still be stolen via network sniffing if Secure is not set.
Why it matters:Relying only on HttpOnly without Secure leaves cookies vulnerable on unencrypted connections.
Quick: Does a cookie without expiration last forever? Commit yes or no.
Common Belief:Cookies without expiration never expire and stay on the device forever.
Tap to reveal reality
Reality:Cookies without expiration are session cookies and are deleted when the browser closes.
Why it matters:Misunderstanding this can cause developers to expect persistent cookies when they actually disappear on browser close.
Quick: Does SameSite='Lax' block all cross-site cookie sending? Commit yes or no.
Common Belief:SameSite='Lax' completely blocks cookies from being sent on cross-site requests.
Tap to reveal reality
Reality:SameSite='Lax' blocks most but allows cookies on top-level GET navigations like clicking links.
Why it matters:Assuming full blocking can lead to security holes or broken functionality.
Expert Zone
1
Some browsers treat missing SameSite attribute as 'Lax' by default, which can break legacy cross-site integrations.
2
Setting cookie expiration far in the future increases risk if the cookie is stolen, so balance persistence with security.
3
HttpOnly does not protect against cross-site scripting that steals cookies via other means like CSRF or browser bugs.
When NOT to use
Avoid relying solely on cookies for sensitive authentication data; use tokens stored in secure storage or server-side sessions instead. For highly sensitive data, consider using short-lived cookies combined with additional verification like multi-factor authentication.
Production Patterns
In production, cookies for authentication are set with Secure, HttpOnly, and SameSite='Strict' flags. Expiration is often short (minutes to hours) with refresh tokens to maintain sessions. Cookies are scoped by domain and path to limit exposure. Developers also monitor cookie usage with security headers like Content Security Policy.
Connections
Session management
Cookie expiration and security are foundational for managing user sessions safely.
Understanding cookie controls helps grasp how sessions persist and stay secure across web requests.
Cross-site scripting (XSS)
HttpOnly cookie flag directly defends against XSS attacks stealing cookies.
Knowing cookie security flags clarifies how web apps defend against common client-side attacks.
Physical mail security
Like sealing a letter to prevent tampering, cookie security flags protect data from unauthorized access.
Recognizing parallels between digital and physical security deepens appreciation for layered protections.
Common Pitfalls
#1Setting cookie expiration as a relative number instead of a timestamp
Wrong approach:setcookie('user', 'abc', 3600); // wrong: 3600 is not a timestamp
Correct approach:setcookie('user', 'abc', time() + 3600); // correct: expiration is current time + 1 hour
Root cause:Confusing expiration parameter as duration instead of absolute timestamp.
#2Omitting Secure flag on cookies for HTTPS sites
Wrong approach:setcookie('session', 'xyz', time() + 3600); // missing 'secure' => true
Correct approach:setcookie('session', 'xyz', [ 'expires' => time() + 3600, 'secure' => true ]);
Root cause:Not realizing cookies sent over HTTP can be intercepted even on HTTPS sites if Secure flag is missing.
#3Setting SameSite to 'None' without Secure flag
Wrong approach:setcookie('id', '123', [ 'samesite' => 'None' ]); // missing Secure flag
Correct approach:setcookie('id', '123', [ 'samesite' => 'None', 'secure' => true ]);
Root cause:Modern browsers require Secure flag when SameSite is 'None' to allow cross-site cookies.
Key Takeaways
Cookies store small pieces of data in browsers and have expiration times to control their lifetime.
Security flags like Secure, HttpOnly, and SameSite protect cookies from theft and misuse in different ways.
In PHP, cookie expiration is set as a timestamp, and security flags are set via an options array in setcookie.
Misunderstanding cookie expiration or security flags can lead to serious vulnerabilities or broken functionality.
Expert use involves combining expiration and security settings carefully to balance usability and protection.