Bird
Raised Fist0
PHPprogramming~10 mins

Setting and reading cookies in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Setting and reading cookies
Start PHP script
↓
Set cookie with setcookie()
↓
Send HTTP headers with cookie
↓
Browser stores cookie
↓
Next request: browser sends cookie
↓
Read cookie from $_COOKIE superglobal
↓
Use cookie value in script
↓
End script
The script sets a cookie which the browser stores and sends back on next requests, allowing the script to read it from $_COOKIE.
Execution Sample
PHP
<?php
setcookie("user", "Alice", time() + 3600);

if (isset($_COOKIE["user"])) {
    echo "User: " . $_COOKIE["user"];
} else {
    echo "No user cookie set.";
}
?>
This code sets a cookie named 'user' with value 'Alice' for 1 hour, then reads and prints it if available.
Execution Table
StepActionEvaluationResult
1Call setcookie("user", "Alice", time()+3600)Sets HTTP header to set cookieCookie header sent to browser
2End script, browser receives cookie headerBrowser stores cookie 'user=Alice'Cookie saved in browser
3Next request sent by browserBrowser sends cookie 'user=Alice' in HTTP headersPHP $_COOKIE['user'] = 'Alice'
4Check if isset($_COOKIE['user'])TrueEnter if block
5Echo 'User: ' . $_COOKIE['user']Concatenate stringsOutput: User: Alice
💡 Script ends after output; cookie persists for 1 hour in browser.
Variable Tracker
VariableStartAfter Step 3After Step 5
$_COOKIE['user']undefinedAliceAlice
Key Moments - 2 Insights
Why does the cookie value appear only on the next request, not immediately after setcookie()?
Because setcookie() sends a header to the browser, which stores the cookie and sends it back on the next request. The $_COOKIE array is populated from incoming request headers, so it won't have the new cookie until the next page load (see execution_table step 3).
What happens if you try to read $_COOKIE['user'] before calling setcookie()?
If the cookie was not previously set and sent by the browser, $_COOKIE['user'] will be undefined or not set. The script must check with isset() to avoid errors (see execution_table step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does the browser send the cookie back to PHP?
AStep 3
BStep 1
CStep 5
DStep 2
💡 Hint
Check the 'Action' and 'Result' columns at step 3 where the browser sends the cookie in HTTP headers.
According to the variable tracker, what is the value of $_COOKIE['user'] before the browser sends the cookie?
AAlice
Bnull
Cundefined
Dempty string
💡 Hint
Look at the 'Start' column for $_COOKIE['user'] in the variable tracker.
If the cookie expiration time is set to time() - 3600, what would happen?
ACookie is set and available immediately
BCookie is deleted or expired immediately
CCookie lasts for 1 hour
DCookie value becomes empty string
💡 Hint
Recall that setting expiration in the past deletes the cookie; see concept flow about cookie lifetime.
Concept Snapshot
setcookie(name, value, expire) sends a cookie header to browser.
Browser stores cookie and sends it back on next requests.
Read cookies in PHP from $_COOKIE superglobal.
$_COOKIE only has cookies sent by browser in current request.
Use isset() to check if cookie exists before reading.
Cookie expires after given time or when deleted.
Full Transcript
This visual execution shows how PHP sets and reads cookies. First, setcookie() sends a header to the browser to store a cookie named 'user' with value 'Alice' for one hour. The browser saves this cookie and sends it back in the next request. PHP reads the cookie from the $_COOKIE array, which is populated from the browser's request headers. The script checks if the cookie exists using isset() and then prints its value. Cookies do not appear in $_COOKIE immediately after setcookie() because the browser must send them back on the next request. Setting a cookie expiration time in the past deletes the cookie. This step-by-step trace helps beginners understand the flow of setting and reading cookies in PHP.

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