Bird
0
0

Identify the error in this PHP code snippet:

medium📝 Debug Q6 of 15
PHP - Sessions and Cookies
Identify the error in this PHP code snippet:
<?php
$_SESSION['user'] = 'John';
session_start();
echo $_SESSION['user'];
?>
Asession_start() must be called before accessing $_SESSION
BSession variable 'user' cannot be a string
Csession_start() should be called after echo
DNo error, code works fine
Step-by-Step Solution
Solution:
  1. Step 1: Check session_start() placement

    Session must be started before reading or writing $_SESSION variables.
  2. Step 2: Identify error cause

    Here, $_SESSION['user'] is set before session_start(), so session data is not properly initialized.
  3. Final Answer:

    session_start() must be called before accessing $_SESSION -> Option A
  4. Quick Check:

    Call session_start() first to use $_SESSION [OK]
Quick Trick: Always call session_start() before $_SESSION use [OK]
Common Mistakes:
  • Setting $_SESSION before session_start()
  • Assuming session auto-starts
  • Ignoring session initialization order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes