0
0
PHPprogramming~15 mins

Setting and reading cookies in PHP - Deep Dive

Choose your learning style9 modes available
Overview - Setting and reading cookies
What is it?
Cookies are small pieces of data stored by a website on your computer to remember information about you. Setting a cookie means telling the browser to save some data, like your name or preferences. Reading a cookie means getting that saved data back when you visit the website again. This helps websites remember you without asking every time.
Why it matters
Without cookies, websites would forget who you are every time you visit, making you log in repeatedly or lose your settings. Cookies solve this by storing small bits of information on your device, creating a smoother and more personal experience. They are essential for things like staying logged in, shopping carts, and language preferences.
Where it fits
Before learning cookies, you should understand how web servers and browsers communicate using HTTP. After cookies, you can learn about sessions, which build on cookies to manage user data more securely and efficiently.
Mental Model
Core Idea
Cookies are like tiny notes a website asks your browser to keep and show back later to remember you.
Think of it like...
Imagine visiting a coffee shop where the barista writes your favorite drink on a sticky note and sticks it on your cup. Next time you come, they see the note and make your drink without asking.
┌─────────────┐       ┌─────────────┐       ┌─────────────┐
│  Browser    │──────▶│  Server     │
│  (Client)   │       │             │
│             │◀──────│             │
└─────────────┘       └─────────────┘
     ▲                      ▲
     │                      │
     │ Set-Cookie header     │
     │                      │
     │                      │
     │                      │
     │ Cookie sent back on next request
     │                      │
Build-Up - 7 Steps
1
FoundationWhat is a cookie in PHP
🤔
Concept: Introduce the basic idea of cookies as small data stored on the user's browser.
A cookie is a small text file saved by the browser. In PHP, you set a cookie using the setcookie() function before any output. For example: setcookie('username', 'Alice', time() + 3600); This tells the browser to save 'username' with value 'Alice' for 1 hour.
Result
The browser stores the cookie and sends it back to the server on future requests within 1 hour.
Understanding that cookies are stored on the client side helps you see why you must set them before output and why they persist across page loads.
2
FoundationHow to read cookies in PHP
🤔
Concept: Learn how to access cookies sent by the browser back to the server.
When a browser sends a request, it includes cookies in the $_COOKIE superglobal array in PHP. You can read a cookie like this: if (isset($_COOKIE['username'])) { echo 'Hello, ' . $_COOKIE['username']; } else { echo 'Hello, guest!'; } This checks if the cookie exists and uses its value.
Result
You see a personalized greeting if the cookie is set, or a default message if not.
Knowing that cookies come back from the browser in $_COOKIE lets you customize responses based on stored data.
3
IntermediateCookie expiration and lifetime
🤔Before reading on: Do you think cookies last forever once set, or do they expire? Commit to your answer.
Concept: Cookies have a lifetime controlled by an expiration time, after which browsers delete them.
When setting a cookie, you specify an expiration timestamp as the third argument to setcookie(). For example: setcookie('theme', 'dark', time() + 86400); // lasts 1 day If you omit expiration, the cookie lasts only for the browser session (until closed).
Result
Cookies disappear after their expiration time or when the browser closes if no expiration is set.
Understanding expiration prevents bugs where cookies unexpectedly vanish or persist too long, affecting user experience.
4
IntermediateCookie scope: path and domain
🤔Before reading on: Do you think cookies are sent to all websites or only specific parts? Commit to your answer.
Concept: Cookies can be limited to specific paths or domains to control where they are sent.
You can set the path and domain parameters in setcookie() to restrict cookies. For example: setcookie('cart', '123', time() + 3600, '/shop'); This cookie is sent only for URLs under '/shop'. Similarly, domain limits cookies to subdomains.
Result
Cookies are sent only to matching URLs, improving security and reducing unnecessary data transfer.
Knowing cookie scope helps you avoid leaking data to unrelated parts of your site or other sites.
5
IntermediateSecure and HttpOnly cookie flags
🤔Before reading on: Do you think cookies are always safe from hackers, or can you make them safer? Commit to your answer.
Concept: Cookies can be marked to be sent only over secure connections and hidden from JavaScript.
You can add flags to cookies: setcookie('session', 'abc123', time() + 3600, '/', '', true, true); The fifth argument 'true' means send only over HTTPS (Secure flag). The sixth 'true' means JavaScript cannot access it (HttpOnly flag).
Result
Cookies become safer, reducing risks of theft via network sniffing or cross-site scripting.
Understanding these flags is key to protecting sensitive data stored in cookies.
6
AdvancedCookie limitations and size constraints
🤔Before reading on: Do you think cookies can store unlimited data or have limits? Commit to your answer.
Concept: Cookies have size limits and browser restrictions that affect how much data you can store.
Browsers limit cookies to about 4KB each and a total number per domain (usually around 20). Storing large data or many cookies can cause failures or data loss. Use cookies only for small pieces of info.
Result
Trying to store too much data in cookies leads to missing or truncated cookies.
Knowing cookie size limits helps you design better data storage strategies, like using sessions or databases for large data.
7
ExpertHow cookies interact with HTTP headers
🤔Before reading on: Do you think cookies are part of the page content or HTTP headers? Commit to your answer.
Concept: Cookies are sent and received via HTTP headers, not page content, affecting when and how you can set them.
When you call setcookie() in PHP, it sends a Set-Cookie header before any HTML output. Browsers store this and send Cookie headers on future requests. If you output HTML before setcookie(), headers are already sent and setting cookies fails. Example: // Correct setcookie('user', 'Bob'); echo 'Welcome'; // Wrong echo 'Welcome'; setcookie('user', 'Bob'); // error: headers already sent
Result
Cookies are set only if headers are sent before output, otherwise PHP errors occur.
Understanding cookies as HTTP headers explains common errors and timing rules in web programming.
Under the Hood
Cookies work by exchanging HTTP headers between the server and browser. The server sends a Set-Cookie header with name, value, and options. The browser saves this data and includes it in Cookie headers on subsequent requests to the same domain and path. PHP accesses these cookies via the $_COOKIE array. Cookies are stored on the client device, so the server relies on the browser to send them back correctly.
Why designed this way?
HTTP is stateless, meaning each request is independent. Cookies were designed to add state by storing small data on the client side without changing the protocol. Using headers keeps cookies separate from page content, allowing browsers and servers to manage them efficiently and securely. Alternatives like URL parameters were less secure and cluttered URLs.
┌───────────────┐          Set-Cookie header          ┌───────────────┐
│    Server     │────────────────────────────────────▶│    Browser    │
│               │                                    │               │
│  PHP script   │                                    │  Stores cookie│
└───────────────┘                                    └───────────────┘
       ▲                                                      │
       │                                                      │
       │                                                      │
       │<──────────────────────── Cookie header ─────────────┘
       │
       │
┌───────────────┐
│    Server     │
│  PHP script   │
│  reads $_COOKIE│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think cookies are stored on the server or the client? Commit to your answer.
Common Belief:Cookies are stored on the server side like session data.
Tap to reveal reality
Reality:Cookies are stored on the client side, in the user's browser, not on the server.
Why it matters:Assuming cookies are server-side can lead to security mistakes and confusion about data persistence.
Quick: Do you think you can set cookies after sending HTML output? Commit to your answer.
Common Belief:You can set cookies anytime during the PHP script, even after output.
Tap to reveal reality
Reality:Cookies must be set before any output because they use HTTP headers, which must be sent first.
Why it matters:Trying to set cookies after output causes errors and cookies won't be saved, breaking functionality.
Quick: Do you think cookies can store large files or sensitive passwords safely? Commit to your answer.
Common Belief:Cookies can safely store any data, including large files and passwords.
Tap to reveal reality
Reality:Cookies have size limits (~4KB) and are visible to the user, so they should never store sensitive data like passwords or large files.
Why it matters:Misusing cookies for sensitive data risks security breaches and performance issues.
Quick: Do you think cookies are sent to all websites or only the site that set them? Commit to your answer.
Common Belief:Cookies are sent to all websites the user visits.
Tap to reveal reality
Reality:Cookies are sent only to the domain and path that set them, not to other websites.
Why it matters:Understanding cookie scope prevents privacy leaks and helps design secure web applications.
Expert Zone
1
Cookies set with the HttpOnly flag cannot be accessed by JavaScript, preventing many cross-site scripting attacks.
2
Browsers may limit the total number of cookies per domain and overall size, causing older cookies to be dropped silently.
3
SameSite cookie attribute controls cross-site request behavior, crucial for preventing CSRF attacks but often misunderstood.
When NOT to use
Cookies are not suitable for storing large or sensitive data. For secure user sessions, use server-side sessions combined with secure cookies. For large data, use databases or local storage. Avoid cookies for critical security tokens without proper flags.
Production Patterns
In production, cookies are used to store session IDs with Secure and HttpOnly flags, user preferences with expiration, and tracking identifiers with SameSite policies. Developers often combine cookies with server-side session management for security and scalability.
Connections
HTTP Headers
Cookies are exchanged via HTTP headers between client and server.
Understanding HTTP headers clarifies how cookies are sent and received, explaining timing and security constraints.
Web Sessions
Sessions build on cookies by storing session IDs in cookies to maintain user state securely on the server.
Knowing cookies helps grasp how sessions track users without storing all data client-side.
Privacy and Security
Cookies relate to privacy laws and security practices controlling data storage and sharing.
Understanding cookies is key to complying with privacy regulations like GDPR and preventing security vulnerabilities.
Common Pitfalls
#1Trying to set a cookie after outputting HTML causes errors.
Wrong approach:
Correct approach:
Root cause:Headers must be sent before any output; setcookie() sends headers, so it must come first.
#2Storing sensitive data like passwords directly in cookies.
Wrong approach:
Correct approach:
Root cause:Cookies are visible and modifiable by users; sensitive data must be protected on the server.
#3Assuming cookies last forever without expiration.
Wrong approach:
Correct approach:
Root cause:Without expiration, cookies last only for the browser session and disappear on close.
Key Takeaways
Cookies are small pieces of data stored on the user's browser to remember information across visits.
In PHP, you set cookies with setcookie() before any output and read them from the $_COOKIE array.
Cookies have expiration times, scope (path and domain), and security flags (Secure, HttpOnly) that control their behavior.
Cookies are sent via HTTP headers, so timing and header rules are critical to avoid errors.
Cookies have size limits and security considerations; use them wisely and combine with server-side sessions for best results.