Bird
0
0

Consider this PHP code:

medium📝 Predict Output Q5 of 15
PHP - Sessions and Cookies
Consider this PHP code:
<?php
session_start();
if (!isset($_SESSION['visits'])) {
  $_SESSION['visits'] = 1;
} else {
  $_SESSION['visits']++;
}
setcookie('visits', $_SESSION['visits'], time() + 3600);
echo $_COOKIE['visits'];
?>

What will be the output on the first page load?
ANotice error for undefined index
B1
C0
D2
Step-by-Step Solution
Solution:
  1. Step 1: Analyze cookie availability on first load

    Cookies set with setcookie() are not available in $_COOKIE until the next request.
  2. Step 2: Check echo statement

    Echoing $_COOKIE['visits'] on first load causes a notice error because it is not set yet.
  3. Final Answer:

    Notice error for undefined index -> Option A
  4. Quick Check:

    Cookie not accessible immediately after setcookie() [OK]
Quick Trick: Cookies appear in $_COOKIE only on next request [OK]
Common Mistakes:
  • Expecting cookie value immediately after setcookie()
  • Ignoring PHP notices for undefined cookie keys
  • Confusing session and cookie timing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes