Bird
0
0

Identify the error in this PHP code snippet:

medium📝 Debug Q14 of 15
PHP - Sessions and Cookies
Identify the error in this PHP code snippet:
<?php
setcookie('theme', 'dark');
session_start();
$_SESSION['theme'] = 'light';
?>
Asession_start() must be called before setcookie()
BNo error, code is correct
C$_SESSION cannot be set after setcookie()
Dsetcookie() must be called before any output
Step-by-Step Solution
Solution:
  1. Step 1: Recall header rules in PHP

    Both setcookie() and session_start() send HTTP headers and must be called before any output.
  2. Step 2: Check order and output

    No output before either function. Order of setcookie() before session_start() is fine; multiple Set-Cookie headers are allowed.
  3. Final Answer:

    No error, code is correct -> Option B
  4. Quick Check:

    Headers before output, order OK [OK]
Quick Trick: Call setcookie() and session_start() before any output [OK]
Common Mistakes:
  • Thinking session_start() must come before setcookie()
  • Ignoring header output rules
  • Assuming $_SESSION depends on setcookie()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes