Bird
Raised Fist0
PHPprogramming~15 mins

How cookies work in PHP - Mechanics & Internals

Choose your learning style10 modes available
Overview - How cookies work
What is it?
Cookies are small pieces of data that websites store on your computer through your browser. They help websites remember you, like keeping you logged in or saving your preferences. When you visit the site again, the browser sends these cookies back to the website. This way, the website can recognize you and provide a smoother experience.
Why it matters
Without cookies, websites would treat every visit as brand new, forgetting who you are each time. This would mean logging in repeatedly, losing shopping carts, and no personalized settings. Cookies solve this by storing small bits of information on your device, making the web feel more personal and efficient.
Where it fits
Before learning about cookies, you should understand how web browsers and servers communicate using HTTP. After cookies, you can explore sessions and authentication methods that build on cookie concepts to manage user identity securely.
Mental Model
Core Idea
Cookies are like name tags your browser wears to websites so they recognize you on return visits.
Think of it like...
Imagine going to a coffee shop where the barista gives you a small card with your name and favorite drink. Next time you come, you show the card, and they remember you instantly without asking again.
┌───────────────┐       ┌───────────────┐
│   Browser     │       │    Website    │
│               │       │               │
│  Stores cookie│◄──────│  Sends cookie │
│  Sends cookie │──────▶│  Sets cookie  │
└───────────────┘       └───────────────┘

Flow:
1. Website sends cookie to browser.
2. Browser stores cookie.
3. On next visit, browser sends cookie back.
4. Website reads cookie to recognize user.
Build-Up - 7 Steps
1
FoundationWhat is a cookie in web terms
🤔
Concept: Introduce the basic idea of a cookie as a small data piece stored by the browser.
A cookie is a tiny text file that a website asks your browser to save. It usually contains information like a user ID or preferences. The browser keeps this file and sends it back to the website on future visits automatically.
Result
You understand that cookies are small data stored on your device by websites.
Understanding that cookies are simple text data stored by browsers is the foundation for all cookie-related concepts.
2
FoundationHow browsers and servers exchange cookies
🤔
Concept: Explain the HTTP headers used to send and receive cookies between browser and server.
When a server wants to store a cookie, it sends a 'Set-Cookie' header in its HTTP response. The browser saves this cookie. On later requests to the same server, the browser includes the cookie in the 'Cookie' header. This exchange happens automatically with every request and response.
Result
You see how cookies travel back and forth in HTTP headers.
Knowing the headers involved clarifies how cookies are passed without user action.
3
IntermediateSetting cookies with PHP code
🤔
Concept: Learn how to create cookies in PHP using the setcookie() function.
This code tells the browser to save a cookie called 'user' with the value 'Alice'. The cookie will last for one hour.
Result
The browser receives the cookie and stores it for future requests.
Understanding how to set cookies in code is essential for controlling user experience.
4
IntermediateReading cookies in PHP scripts
🤔
Concept: Learn how to access cookie values sent by the browser in PHP.
This code checks if the 'user' cookie exists and greets the user accordingly.
Result
The script personalizes output based on stored cookie data.
Knowing how to read cookies lets your website remember users and customize content.
5
IntermediateCookie attributes and security flags
🤔Before reading on: Do you think cookies are always safe to store sensitive data? Commit to your answer.
Concept: Introduce cookie options like expiration, path, domain, Secure, and HttpOnly flags.
time() + 3600, 'path' => '/', 'secure' => true, // only send over HTTPS 'httponly' => true, // inaccessible to JavaScript 'samesite' => 'Lax' // restrict cross-site sending ]); ?> These options control when and how cookies are sent and improve security.
Result
Cookies become safer and more controlled in their behavior.
Understanding cookie attributes is key to protecting user data and preventing attacks.
6
AdvancedHow cookies enable sessions and login states
🤔Before reading on: Do you think cookies store your password directly? Commit to your answer.
Concept: Explain how cookies store session IDs, not sensitive data, to keep users logged in securely.
Websites create a unique session ID and store it in a cookie. The server keeps user data linked to this ID. When the browser sends the cookie, the server knows who the user is without storing sensitive info in the cookie itself. This protects privacy and security.
Result
Users stay logged in without exposing passwords or personal data in cookies.
Knowing that cookies hold only session IDs prevents common security mistakes.
7
ExpertCookie scope, conflicts, and browser behavior
🤔Before reading on: Can two different websites read each other's cookies? Commit to your answer.
Concept: Explore how domain, path, and browser rules isolate cookies and how conflicts are resolved.
Cookies are scoped by domain and path, so only matching URLs send cookies. Browsers prevent one site from reading another's cookies for privacy. If multiple cookies share a name but differ in path or domain, browsers send all matching cookies, and servers decide which to use. This can cause subtle bugs if not managed carefully.
Result
You understand cookie isolation and how to avoid naming conflicts.
Understanding cookie scope and browser rules helps prevent security leaks and bugs in complex sites.
Under the Hood
When a server responds, it includes a 'Set-Cookie' header with cookie data. The browser parses this header and stores the cookie in its internal cookie store, associating it with the domain and path. On subsequent requests to matching URLs, the browser automatically adds a 'Cookie' header with all relevant cookies. The server reads this header to identify the user or preferences. Browsers enforce rules to isolate cookies by domain and path and apply security flags to control cookie visibility and transmission.
Why designed this way?
Cookies were designed to work within the stateless HTTP protocol to provide a way to remember users between requests. Early web had no memory, so cookies added a simple, standardized method to store small data on the client side. The design balances simplicity, privacy, and security by limiting cookie size, scope, and access. Alternatives like URL rewriting were less secure and more cumbersome.
┌───────────────┐
│   Server      │
│  (sends Set-  │
│  Cookie header)│
└───────┬───────┘
        │
        ▼
┌───────────────┐
│   Browser     │
│ Stores cookie │
│ in cookie jar │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│   Browser     │
│ Sends Cookie  │
│ header on    │
│ next request │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│   Server      │
│ Reads Cookie  │
│ header to    │
│ identify user│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do cookies store your password directly? Commit to yes or no.
Common Belief:Cookies store sensitive data like passwords so the website remembers you.
Tap to reveal reality
Reality:Cookies usually store only a session ID or token, not sensitive data like passwords.
Why it matters:Storing passwords in cookies risks theft and hacking, leading to security breaches.
Quick: Can one website read cookies set by another website? Commit to yes or no.
Common Belief:Cookies are shared across all websites you visit.
Tap to reveal reality
Reality:Cookies are isolated by domain; one website cannot read another's cookies.
Why it matters:Believing cookies are shared can cause privacy fears or incorrect debugging.
Quick: Do cookies last forever once set? Commit to yes or no.
Common Belief:Cookies stay on your device forever unless you delete them manually.
Tap to reveal reality
Reality:Cookies have expiration times and can be session-only, disappearing when the browser closes.
Why it matters:Misunderstanding cookie lifespan can cause bugs in user experience and data retention.
Quick: Does setting the Secure flag on a cookie mean it is encrypted? Commit to yes or no.
Common Belief:The Secure flag encrypts the cookie data itself.
Tap to reveal reality
Reality:The Secure flag only ensures the cookie is sent over HTTPS, not that the cookie content is encrypted.
Why it matters:Thinking Secure encrypts data may lead to false security assumptions.
Expert Zone
1
Cookies with the SameSite attribute help prevent cross-site request forgery (CSRF) attacks by controlling when cookies are sent.
2
Browsers limit the total number and size of cookies per domain, which can cause unexpected cookie eviction if limits are exceeded.
3
HttpOnly cookies cannot be accessed by JavaScript, reducing the risk of cross-site scripting (XSS) attacks stealing cookies.
When NOT to use
Cookies are not suitable for storing large amounts of data or highly sensitive information like passwords. Alternatives include server-side sessions, localStorage for non-sensitive client data, or secure tokens with short lifetimes. For strict privacy needs, consider token-based authentication without cookies.
Production Patterns
In real-world systems, cookies are used to store session IDs linked to server-side session stores. Secure and HttpOnly flags are always set for authentication cookies. SameSite=Lax or Strict is used to prevent CSRF. Cookies are rotated and invalidated on logout or timeout. Developers carefully manage cookie paths and domains to avoid conflicts in multi-subdomain applications.
Connections
HTTP Protocol
Cookies build on HTTP headers to add statefulness to the stateless protocol.
Understanding HTTP basics helps grasp how cookies fit into web communication.
Session Management
Cookies are the foundation for managing user sessions and login states.
Knowing cookies clarifies how sessions persist user identity across requests.
Human Memory and Recognition
Cookies mimic how humans remember people by recognizing a small token (like a face or name).
This cross-domain link shows how digital systems replicate natural recognition processes.
Common Pitfalls
#1Storing sensitive data like passwords directly in cookies.
Wrong approach:
Correct approach:
Root cause:Misunderstanding that cookies are secure storage rather than simple data holders.
#2Not setting the HttpOnly flag on authentication cookies.
Wrong approach:
Correct approach: true]); ?>
Root cause:Lack of awareness about JavaScript access to cookies and XSS risks.
#3Assuming cookies persist after browser closes without setting expiration.
Wrong approach:
Correct approach:
Root cause:Not knowing the difference between session cookies and persistent cookies.
Key Takeaways
Cookies are small pieces of data stored by browsers to help websites remember users and preferences.
They work by exchanging HTTP headers between the server and browser automatically on requests and responses.
Cookies should never store sensitive data directly; instead, they hold session IDs that link to secure server data.
Security flags like HttpOnly, Secure, and SameSite are essential to protect cookies from common web attacks.
Understanding cookie scope, expiration, and browser rules is key to building reliable and safe web applications.

Practice

(1/5)
1. What is the primary purpose of cookies in PHP?
easy
A. To execute server-side scripts
B. To style web pages dynamically
C. To create database connections
D. To store small pieces of data on the user's computer

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 D
  4. Quick Check:

    Cookies store data = B [OK]
Hint: Cookies save data on user device, not server tasks [OK]
Common Mistakes:
  • Confusing cookies with server-side code execution
  • Thinking cookies style web pages
  • Assuming cookies manage database connections
2. Which of the following is the correct syntax 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 PHP function to set cookies

    The correct PHP function is setcookie() with parameters as strings.
  2. Step 2: Check syntax correctness

    setcookie('user', 'John'); uses correct function name and quotes around parameters, making it valid syntax.
  3. Final Answer:

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

    Correct function and quotes = A [OK]
Hint: Use setcookie() with quoted strings for name and value [OK]
Common Mistakes:
  • Using wrong function names like cookie_set or set_cookie
  • Forgetting quotes around cookie name or value
  • Passing variables without quotes incorrectly
3. What will be the output of the following PHP code?
setcookie('color', 'blue');
if(isset($_COOKIE['color'])) {
echo $_COOKIE['color'];
} else {
echo 'No cookie set';
}
medium
A. blue
B. No cookie set
C. Undefined index error
D. Syntax error

Solution

  1. Step 1: Understand when cookies are available

    Cookies set by setcookie() are available on the next page load, not immediately in the same script.
  2. Step 2: Check the condition in the code

    Since the cookie is not yet set in $_COOKIE during this script run, isset($_COOKIE['color']) is false, so it prints 'No cookie set'.
  3. Final Answer:

    No cookie set -> Option B
  4. Quick Check:

    Cookie available next request = A [OK]
Hint: Cookies appear in $_COOKIE on next page load, not immediately [OK]
Common Mistakes:
  • Expecting cookie immediately after setcookie() in same script
  • Assuming $_COOKIE is updated instantly
  • Confusing cookie setting with session variables
4. Identify the error in this PHP code snippet that tries to set a cookie:
setcookie('theme', 'dark', time() + 3600)
echo 'Cookie set!';
medium
A. Missing semicolon after setcookie() call
B. Incorrect function name
C. Wrong parameter order in setcookie()
D. Cookies cannot be set with expiration time

Solution

  1. Step 1: Check PHP syntax rules

    Each PHP statement must end with a semicolon (;). The setcookie() call is missing this.
  2. Step 2: Verify function name and parameters

    The function name and parameters are correct, and expiration time is valid.
  3. Final Answer:

    Missing semicolon after setcookie() call -> Option A
  4. Quick Check:

    Semicolon missing = C [OK]
Hint: Always end PHP statements with semicolon [OK]
Common Mistakes:
  • Forgetting semicolon at end of function calls
  • Thinking expiration time is invalid
  • Confusing function names
5. You want to create a cookie that lasts for 7 days, is only accessible over HTTPS, and cannot be accessed by JavaScript. Which of the following setcookie() calls correctly achieves this?
hard
A. setcookie('session', 'active', time() + 604800);
B. setcookie('session', 'active', time() + 604800, '/', '', false, true);
C. setcookie('session', 'active', time() + 604800, '/', '', true, true);
D. setcookie('session', 'active', time() + 604800, '/', '', true, false);

Solution

  1. Step 1: Calculate expiration time for 7 days

    7 days = 7 * 24 * 3600 = 604800 seconds, so time() + 604800 is correct.
  2. Step 2: Set secure and httponly flags

    To make cookie HTTPS-only, set the secure flag to true. To improve security, httponly should also be true.
  3. Step 3: Check options

    setcookie('session', 'active', time() + 604800, '/', '', true, true); sets secure and httponly to true, matching requirements. Others either disable secure or httponly or omit parameters.
  4. Final Answer:

    setcookie('session', 'active', time() + 604800, '/', '', true, true); -> Option C
  5. Quick Check:

    Secure and httponly true for HTTPS cookie = D [OK]
Hint: Use secure=true and httponly=true for HTTPS cookies [OK]
Common Mistakes:
  • Not setting secure flag to true for HTTPS-only cookies
  • Omitting httponly flag for security
  • Incorrect expiration time calculation
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