Bird
Raised Fist0
PHPprogramming~10 mins

How cookies work in PHP - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - How cookies work
Client sends HTTP request
↓
Server checks for cookies
↓
Server sends HTTP response with Set-Cookie header
↓
Browser stores cookie
↓
Browser sends cookie with next requests
↓
Server reads cookie from request
↓
Repeat cycle
This flow shows how a browser and server exchange cookies through HTTP requests and responses.
Execution Sample
PHP
<?php
// Set a cookie
setcookie('user', 'Alice', time() + 3600);

// Read cookie
if (isset($_COOKIE['user'])) {
    echo 'Hello ' . $_COOKIE['user'];
}
?>
This PHP code sets a cookie named 'user' and then reads it to greet the user.
Execution Table
StepActionServer BehaviorBrowser BehaviorOutput
1Client sends first HTTP requestNo cookie receivedNo cookie stored yetNo output
2Server runs setcookie('user', 'Alice', time()+3600)Sends Set-Cookie header: user=Alice; expires=+1 hourReceives response with Set-Cookie headerNo output yet
3Browser stores cookie 'user=Alice'No actionStores cookie for domainNo output
4Client sends second HTTP requestReceives cookie 'user=Alice' in request headersSends cookie with requestNo output
5Server checks $_COOKIE['user']Finds 'user' cookie with value 'Alice'No actionOutputs: Hello Alice
6End of scriptResponse sent with greetingDisplays greetingHello Alice
💡 Execution stops after server sends greeting and browser displays it.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
$_COOKIE['user']undefinedundefinedundefined'Alice''Alice''Alice'
Cookie stored in browsernonenone'user=Alice''user=Alice''user=Alice''user=Alice'
Key Moments - 2 Insights
Why doesn't the cookie appear in $_COOKIE immediately after setcookie()?
Because setcookie() only sends a header to the browser; the cookie is stored on the client and sent back on the next request, as shown between steps 2 and 4 in the execution_table.
How does the browser know to send the cookie back to the server?
The browser stores the cookie after receiving the Set-Cookie header (step 3) and automatically includes it in the headers of subsequent requests (step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the server first receive the cookie from the browser?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Check the 'Server Behavior' column to see when the cookie is received in the request headers.
According to variable_tracker, what is the value of $_COOKIE['user'] after the first request?
AAlice
Bnull
Cundefined
Dempty string
💡 Hint
Look at the 'After Step 2' column for $_COOKIE['user'] in variable_tracker.
If the cookie expiration time is set to time() - 3600, what would happen in the execution flow?
ABrowser deletes the cookie immediately
BBrowser stores cookie normally
CServer ignores the cookie
DCookie value changes to empty string
💡 Hint
Recall that setting expiration in the past causes the browser to delete the cookie.
Concept Snapshot
PHP cookies are small data stored on the browser.
Use setcookie() to send cookies from server to browser.
Browser stores cookies and sends them back with requests.
$_COOKIE array holds cookies sent by browser.
Cookies appear in $_COOKIE only on next request after setcookie().
Full Transcript
This visual trace shows how cookies work in PHP. First, the client sends a request without cookies. The server uses setcookie() to send a cookie in the response header. The browser stores this cookie and sends it back with the next request. The server reads the cookie from $_COOKIE and can use it, for example, to greet the user. Cookies are stored on the client and only appear in $_COOKIE on subsequent requests after being set. This cycle repeats with each request and response.

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