Bird
Raised Fist0
PHPprogramming~15 mins

Setting and reading cookies in PHP - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using cookies in PHP?
easy
A. To store small pieces of data on the user's computer
B. To execute server-side scripts
C. To connect to a database
D. To style the webpage

Solution

  1. Step 1: Understand what cookies do

    Cookies save small data on the user's computer to remember information like preferences or login status.
  2. Step 2: Identify the correct purpose

    Among the options, only storing small data on the user's computer matches the purpose of cookies.
  3. Final Answer:

    To store small pieces of data on the user's computer -> Option A
  4. Quick Check:

    Cookies = store small data [OK]
Hint: Cookies save small data on user devices [OK]
Common Mistakes:
  • Confusing cookies with server-side code execution
  • Thinking cookies connect to databases
  • Assuming cookies control webpage style
2. Which of the following is the correct way to set a cookie named user with value John in PHP?
easy
A. setcookie('user', 'John');
B. cookie_set('user', 'John');
C. set_cookie('user', 'John');
D. setcookie(user, John);

Solution

  1. Step 1: Recall the correct function name and syntax

    The PHP function to set cookies is setcookie(), which takes the cookie name and value as strings.
  2. Step 2: Check the options for correct syntax

    Only setcookie('user', 'John'); uses the correct function name and quotes around name and value.
  3. Final Answer:

    setcookie('user', 'John'); -> Option A
  4. Quick Check:

    Use setcookie() with quoted strings [OK]
Hint: Use setcookie() with quotes around name and value [OK]
Common Mistakes:
  • Using wrong function names like cookie_set or set_cookie
  • Not quoting the cookie name and value
  • Confusing cookie setting with reading
3. What will be the output of the following PHP code if the cookie color is set to blue?
<?php
if (isset($_COOKIE['color'])) {
    echo $_COOKIE['color'];
} else {
    echo 'No color set';
}
?>
medium
A. color
B. No color set
C. Error: Undefined index
D. blue

Solution

  1. Step 1: Check if the cookie 'color' exists

    The code uses isset() to check if $_COOKIE['color'] is set. Since the cookie is set to 'blue', this condition is true.
  2. Step 2: Output the cookie value

    Because the cookie exists, the code echoes its value, which is 'blue'.
  3. Final Answer:

    blue -> Option D
  4. Quick Check:

    Cookie exists, so output its value [OK]
Hint: Check isset before reading cookie to avoid errors [OK]
Common Mistakes:
  • Assuming cookie is not set and printing default
  • Not using isset and causing undefined index error
  • Confusing cookie name with its value
4. Identify the error in this PHP code that tries to read a cookie named session:
<?php
echo $_COOKIE['session'];
?>
medium
A. Cookie name should be uppercase
B. Wrong function used to read cookie
C. Missing check if cookie exists before reading
D. Cookies cannot be read in PHP

Solution

  1. Step 1: Understand cookie reading best practice

    Directly accessing $_COOKIE['session'] without checking if it exists can cause an undefined index notice if the cookie is not set.
  2. Step 2: Identify the missing check

    The code should use isset($_COOKIE['session']) before echoing to avoid errors.
  3. Final Answer:

    Missing check if cookie exists before reading -> Option C
  4. Quick Check:

    Always check isset() before reading cookie [OK]
Hint: Always check isset() before using $_COOKIE values [OK]
Common Mistakes:
  • Ignoring isset() check causing warnings
  • Thinking cookie names are case sensitive in $_COOKIE
  • Believing cookies cannot be read in PHP
5. You want to set a cookie named theme with value dark that expires in 7 days. Which code correctly sets this cookie?
hard
A. setcookie('theme', 'dark', time() + 60);
B. setcookie('theme', 'dark', time() + 7 * 24 * 60 * 60);
C. setcookie('theme', 'dark', 7);
D. setcookie('theme', 'dark', time() - 7 * 24 * 60 * 60);

Solution

  1. Step 1: Calculate expiration time for 7 days

    7 days in seconds = 7 * 24 hours * 60 minutes * 60 seconds = 604800 seconds.
  2. Step 2: Use time() plus 7 days for expiration

    The expiration parameter in setcookie() should be current time plus 604800 seconds.
  3. Step 3: Check options for correct expiration

    setcookie('theme', 'dark', time() + 7 * 24 * 60 * 60); correctly uses time() + 7 * 24 * 60 * 60. setcookie('theme', 'dark', time() + 60); sets only 60 seconds, C uses 7 (invalid), D sets a past time (cookie expires immediately).
  4. Final Answer:

    setcookie('theme', 'dark', time() + 7 * 24 * 60 * 60); -> Option B
  5. Quick Check:

    Expire = now + 7 days in seconds [OK]
Hint: Expire time = time() + days * 86400 seconds [OK]
Common Mistakes:
  • Using small numbers like 7 or 60 instead of seconds
  • Setting expiration in the past
  • Forgetting to add time() to expiration
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard